Skip to content
Advertisement

Reverse iteration in a jQuery Object?

 var   test_data =  {'hr' : [1, 'Hour'], 'min' : [60, 'Minute'], 's' : [3600, 'Second']}

Now while I iterate, I want to get ‘s’ first-

$.each(test_data, function(i, j) {
         // I need to get 's' first
});

I have tried test_data.revers() which does not work. Any solution?

Advertisement

Answer

For a defined order, you could sort the keys of the object and iterate them in descending order of the first value of the array.

var data = { hr: [1, 'Hour'], min: [60, 'Minute'], s: [3600, 'Second'] };

for (const key of Object.keys(data).sort((a, b) => data[b][0] - data[a][0])) {
    console.log(key, ...data[key]);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement