Hols1990
Hols1990

Reputation: 45

Javascript - Sort object by multiple values

var data = {
  "input": [{
      "countA": 1,
      "countB": 10
    },
    {
      "countA": 15,
      "countB": 13
    },
    {
      "countA": 26,
      "countB": 24
    },
    {
      "countA": 6,
      "countB": 25
    },
    {
      "countA": 15,
      "countB": 20
    }
  ]
};

var sorted = data.input.sort(function(a, b) {
  return a['countB'] < b['countB'] ? 1 : -1;
});

console.log(sorted);

The outcome after the first sorting should be after another sorting:

[
    {
        "countA": 6,
        "countB": 25
    },
    {
        "countA": 15,
        "countB": 20
    },
    {
        "countA": 1,
        "countB": 10
    }
    {
        "countA": 26,
        "countB": 24
    },
    {
        "countA": 15,
        "countB": 13
    }
]

So, it should be the highest of "countB" and then descending as long as "countB" is higher than "countA". So far I tried multiple ways, but there's no outcome so far.

Thanks for any help!

Upvotes: 2

Views: 88

Answers (2)

Cid
Cid

Reputation: 15247

You can first extract the values of the array when "countb" >= "countA", sort that array then add the remaining values at the end (note that for order is kept for when "countb" < "countA") :

var data = {
  "input": [{
      "countA": 1,
      "countB": 10
    },
    {
      "countA": 15,
      "countB": 13
    },
    {
      "countA": 26,
      "countB": 24
    },
    {
      "countA": 6,
      "countB": 25
    },
    {
      "countA": 15,
      "countB": 20
    }
  ]
};

const ElementsToSort = data.input.filter(elem => elem.countA <= elem.countB);
const RemainingElements = data.input.filter(elem => ElementsToSort.indexOf(elem) < 0);

// sort as you did
const PartiallySorted = ElementsToSort.sort(function(a, b) {
  return a['countB'] < b['countB']
          ? 1
          : a['countB'] > b['countB']
            ? -1
            : 0;
});


//add the remaining values
const sorted = PartiallySorted.concat(RemainingElements);
console.log(sorted);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386520

You could sort by the result of the comparison of countB > countA and then by the value of countB.

const
    data = [{ countA: 1, countB: 10 }, { countA: 15, countB: 13 }, { countA: 26, countB: 24 }, { countA: 6, countB: 25 }, { countA: 15, countB: 20 }];

data.sort((a, b) =>
    (b.countB > b.countA) - (a.countB > a.countA) ||
    b.countB - a.countB
);

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

Upvotes: 1

Related Questions