0

I use the following construction to iterate through my object in a sorted order. I want to keep the keys in my object, since I want to be able to directly access properties.

var object = {
    "1111": "value1111",
    "300": "value300",
    "2": "value2",
    "4": "value4"
}

$.each(Object.keys(object).sort(function(a, b) {return a - b;}), function(index, key) {
    value = object[key];

    console.log(key + ': ' +  value);    
});

http://jsfiddle.net/qpjdv6hs/2/

Without jQuery:

var keys = Object.keys(object).sort(function(a, b) {return a - b;});
for (var index = 0; index < keys.length; index++) {
    var key = keys[index];
    var value = object[key];

    console.log(key + ': ' +  value);    
}

http://jsfiddle.net/L69bsevb/1/

Is this a good way to do this or does jQuery provide something better? How would I create my own "$.eachSorted" function to use it as comfortable as $.each?

EDIT:

I think I made it:

function eachSorted(object, sortCallback, callback) {

    var keys = Object.keys(object).sort(sortCallback);

    for (var i = 0; i < keys.length; i++) {
        if (callback.call(object[keys[i]], keys[i], object[keys[i]]) === false)
            break;
    }

    return object;
}

function mySort(a, b) {
    return a - b;
}

var object = {
    "1111": "value1111",
    "300": "value300",
    "2": "value2",
    "4": "value4"
}

eachSorted(object, mySort, function(key, value) {
    console.log(key + ': ' + value);
});

http://jsfiddle.net/y62Lqwhz/2/

Any objections?

tyftler
  • 419
  • 5
  • 9
  • How about not using jQuery to iterate over an object? You're worried about optimizing your code, but you're using a rather heavy library to do something very simple. – Cerbrus Oct 27 '14 at 08:09
  • But with `for (key in object)` it still is not sorted, I had to do the same. – tyftler Oct 27 '14 at 08:11
  • 1
    Why not `var keys = Object.keys(object).sort(function(a, b) { return a - b});` with a `for (var i = 0; i < keys.length; i++) { ... }` ? – TenorB Oct 27 '14 at 08:13
  • @Cerbrus You marked it as duplicate but please look at my questions. – tyftler Oct 27 '14 at 08:15

0 Answers0