Freddy Freddy -4 years ago 74
Javascript Question

Sorting an array of objects by value

I'm trying to sort an array of objects, which is huge.

I have created the following functions. I have a compare function that looks like this:

WordCounter.prototype.compare = function(a, b) {
if (Object.values(a) < Object.values(b)) {
return -1;
}
if (Object.values(a) > Object.values(b)) {
return 1;
}
return 0;
};


I then reference it in this function:

WordCounter.prototype.sortArray = function(array) {

this.sortedArray = array.sort(this.compare);
};


I then iterate over the array using the below function, it does sort the objects a bit but it seems to do it in chunks:

WordCounter.prototype.returnWords = function(array) {
for (var key in array) {
return array[key];
}
};


Here is some dummy data for reference, there are actually thousands of objects in the array though:

[{tongues: 1}, {unpleasant: 50}, {sneak: 13}, {marched: 12}, {flaming: 2}]


I need to sort it like this:

[{unpleasant: 50}, {sneak: 13}, {marched: 12}, {flaming: 2}, {tongues: 1}]


Any idea why it is only sorting a little bit and not the whole array of hashes?

Answer Source

You can use a helper function getValue to get a value from an object, assuming it has just one property, and sort by that:

function getValue(obj) {
    for (let key in obj) return obj[key]; // return any value found in the object
}

// Sample data
var arr = [{tongues: 1}, {unpleasant: 50}, {sneak: 13}, {marched: 12}, {flaming: 2}];

// Sort it
arr.sort((a, b)  => getValue(b) - getValue(a));

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download