2

I have array with keys that could be either real strings

var array = {
    'Blue' : 1,
    'Red'  : 2,
    'Green': 3
}

or it could be numbers but sometimes floats considered as strings, I guess because it's not an array but an object:

var array = {
    9     : 1,
    '9.5' : 2,
    10    : 3
    '10.5': 4
}

This one is not really an array so I need to sort it if explicitly if I want to keep the original order:

$.each(Object.keys(array).sort(function(a, b) {
    var anum = parseFloat(a),
        bnum = parseFloat(b);
    return anum - bnum;
}), function(index, value) {
    ……
});

if I don't do that, my array is:

var array = {
    9     : 1,
    10    : 3,
    '9.5' : 2
    '10.5': 4
}

I need to keep it sorted. My solution is working well but I need to check if the keys are numbers or string. If they are string, I don't need to sort the array. Something like:

$.each(/*if my array has numbers as keys I sort the array as above, else just loop*/,
function(index, value) {
    ……
});
Cyril F
  • 1,247
  • 3
  • 16
  • 31

1 Answers1

6

Really shouldn't call that object 'array', but:

if(Object.keys(array).every(key => !isNaN(key)){ //sort }
chrispy
  • 3,552
  • 1
  • 11
  • 19