phpricardo
phpricardo

Reputation: 131

Order Object by Value in Javascript

I have the following object in the qualification and I am not getting any indication of the key. I need to sort by value.

enter image description here

I did so:

let keysSorted = Object.values (arrCambo) .sort (function (a, b) {return arrCambo [a] -arrCambo [b]}); let sorted = keysSorted.sort ();

Generally, return is an array in which I lose the original values of the object I need!

Upvotes: 0

Views: 109

Answers (1)

Tarabass
Tarabass

Reputation: 3152

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};

var sortable= [];

for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

source

Upvotes: 1

Related Questions