Freddy
Freddy

Reputation: 1229

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?

Upvotes: 2

Views: 87

Answers (1)

trincot
trincot

Reputation: 349956

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; }

Upvotes: 2

Related Questions