Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.each: reordering array

I've been fiddling around with arrays and array ordering recently and stumbled across something peculiar.

Take this situation:

arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";

$.each(arr, function (key, val) {
    $(body).html(key + " => " + val);
});

Now, we should hope for the following results:

1 => one
2 => two
105 => three
4 => four

Right? Unfortunately not. I am receiving a numeric sorting which results in index 105 being the last item in the sequence. Anybody have an idea of how I can overcome this problem? Words of guidance are very much appreciated, thank you.

like image 410
nderjung Avatar asked Dec 27 '22 17:12

nderjung


1 Answers

That's not an Array. It's an Object. And as such, there is no guaranteed order.

To guarantee some sort of sequence, you could define the sequence in an Array, then iterate that Array, selecting the index of each array value from the object.

arr = {};
arr[1] = "one";
arr[2] = "two";
arr[105] = "three";
arr[4] = "four";

var order = [1,2,105,4];

$.each(order, function(i,val) {
    console.log( val + '=>' + arr[ val ] );
});
like image 77
user113716 Avatar answered Jan 04 '23 23:01

user113716