Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a list items which are draggable and each one has data id attribute so I can detect their order.

So in normal order they look like this:

<ol>
   <li data-id='0'>Apple</li>
   <li data-id='1'>Banana</li>
   <li data-id='2'>Cake</li>
   <li data-id='3'>Tea</li>
   <li data-id='4'>Biscuit</li>
</ol>

I also have an array the same length as the number of list items which contains data for each list item and its in normal order on the beginning just like the list items.

So after some of my list items are dragged, their order changes, so I need to reorder the data in my array in the same way.

So lets say some list items have been dragged and their order (which I can detect with data-id attribute) now looks like this:

<ol>
   <li data-id='0'>Apple</li>
   <li data-id='2'>Cake</li>
   <li data-id='1'>Banana</li>
   <li data-id='4'>Biscuit</li>
   <li data-id='3'>Tea</li>
</ol>

So I need to change the order in my array the same way.

How can I achieve that?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You could do something like this:

var ordered_array = $('ol li').map(function() {
    return your_array[$(this).data('id')];
}).get();
share|improve this answer

Don't use an array for the data itself, it would be rather hard to maintain the order (keeping track of each reordering). Instead, use an object where you store the data by it's id (OK, that object could even be an array for numeric ids) and an array where you store the order of ids:

var data = {
    0: …,
    1: …
};
var order = $(that_ol).children().map(function() {
    return $(this).attr("data-id");
}).get();

And in case you really need the data in an array, just use

$.map(order, function(id) { return data[id]; })
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.