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.
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 ] );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With