JQuery.each: reordering array

I recently dealt with arrays and arrays, and came 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 must hope for the following results:

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

Right? Unfortunately not. I get a numerical sort, which causes index 105 be the last element in the sequence. Does anyone have an idea how I can overcome this problem? The words of leadership are greatly appreciated, thank you.

+4
source share
2 answers

This is not an array. This is an object. And as such, there is no guaranteed order.

To guarantee some sequence, you can define a sequence in an array, and then iterate over this array by 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 ] ); }); 
+9
source

Perhaps you could try this instead:

 arr = [ ['1', 'one'] , ['2', 'two'] , ['105', 'three'] , ['4', 'four'] ]; $.each(arr, function(key, values) { $(body).html(values[0] + " => " + values[1]); }); 
0
source

All Articles