JavaScript array with decimal index

I have a code:

var arr = {"1":["val"],"1.5":["val"],"2":["val"],"2.5":["val"],"3":["val"]};

jQuery.each( arr, function( index, value ) {
    console.log(index + ':' + value)
});

I need to display the each element that how is in array, but I get:

1:val
2:val
3:val
1.5:val
2.5:val

But I need to get it in this form:

1:val
1.5:val
2:val
2.5:val
3:val

Any ideas?

Answers


That isn't an array, it's a non-array object. Non-array objects have no intrinsic order.* To impose order on them, you get the keys (property names), put them in order, then loop over those names. Something like this:

var arr = {"1":["val"],"1.5":["val"],"2":["val"],"2.5":["val"],"3":["val"]};

jQuery.each( Object.keys(arr).sort(sortNumerically), function( index, name ) {
    console.log(name + ':' + arr[name])
});

// Somewhere reusable
function sortNumerically(a, b) {
    var anum = parseFloat(a),
        bnum = parseFloat(b);
    return anum - bnum;
}

Live Example | Source

Object.keys is an ES5 function that gives you an array of the names of the "own" enumerable properties of an object, as an array. (You can add a shim for it on pre-ES5 engines.) Array#sort sorts arrays in place. (The default sort is lexigraphic, so I've put in a function to do a numeric comparison.) Then we loop through the sorted array, examining the object's properties.


(* For that matter, JavaScript's standard arrays only have order by convention, e.g., the numeric relationship of the array indexes. Except for when engines do optimizations on them, they're not really arrays, nor are the entries necessarily stored in numeric order.)


Need Your Help

Matlab - Improving efficiency of file reading method

performance matlab import io vectorization

I'm writing a Matlab script which begins by reading a space delimited .log file into a cell array . Column headers in the file are all strings, but data types throughout the file are mixed, so for

Android - Text overlays icon on toggle button

android android-layout user-interface samsung-mobile togglebutton

I have a toggle button with an icon and text as shown above (pointed at with the green arrow). Most devices I have tested worked just fine.