Sort Array of objects by two properties in JavaScript



Suppose, we have an array of objects like this −

const arr = [
   { resVal: "25FA15", resFlow: 49, resName: "Rendimiento Tri−Seal
   Completo", resPhoto: "Tri−Sealseries.png", resHP: 1.5 },
   { resVal: "25FA2", resFlow: 52, resName: "Rendimiento Tri−Seal
   Completo", resPhoto: "Tri−Sealseries.png", resHP: 2 },
   { resVal: "45FA2", resFlow: 53, resName: "Rendimiento Hi−Cap
   Completo", resPhoto: "HighCapseries.png", resHP: 2 },
   { resVal: "35FA2", resFlow: 59, resName: "Rendimiento Hi−Cap
   Completo", resPhoto: "HighCapseries.png", resHP: 2 }
];

We are required to write a JavaScript function that takes in one such array of objects. The function should sort this array based on two different properties −

  • sort by the higher "resFlow" value,

  • but with the lowest "resHP" value.

Approach

We are using a chained approach for a specified order of keys and their sort order.

The array is sorted by the properties −

  • resHP, ascending and

  • resFlow, descending.

It works with calculating the delta and this reflects the relation of the two objects. If the value is zero, then the two values are equal and the next delta is calculated and returned.

Example

The code for this will be −

const arr = [
   { resVal: "25FA15", resFlow: 49, resName: "Rendimiento Tri−Seal
   Completo", resPhoto: "Tri−Sealseries.png", resHP: 1.5 },
   { resVal: "25FA2", resFlow: 52, resName: "Rendimiento Tri−Seal
   Completo", resPhoto: "Tri−Sealseries.png", resHP: 2 },
   { resVal: "45FA2", resFlow: 53, resName: "Rendimiento Hi−Cap
   Completo", resPhoto: "HighCapseries.png", resHP: 2 },
   { resVal: "35FA2", resFlow: 59, resName: "Rendimiento Hi−Cap
   Completo", resPhoto: "HighCapseries.png", resHP: 2 }
];
const sortByTwo = (arr = []) => {
   arr.sort((a, b) => {
      return a.resHP − b.resHP || b.resFlow − a.resFlow;
   });
};
sortByTwo(arr);
console.log(arr);

Output

And the output in the console will be −

[
   {
      resVal: '25FA15',
      resFlow: 49,
      resName: 'Rendimiento Tri−Seal Completo',
      resPhoto: 'Tri−Sealseries.png',
      resHP: 1.5
   },
   {
      resVal: '35FA2',
      resFlow: 59,
      resName: 'Rendimiento Hi−Cap Completo',
      resPhoto: 'HighCapseries.png',
      resHP: 2
   },
   {
      resVal: '45FA2',
      resFlow: 53,
      resName: 'Rendimiento Hi−Cap Completo',
      resPhoto: 'HighCapseries.png',
      resHP: 2
   },
   {
      resVal: '25FA2',
      resFlow: 52,
      resName: 'Rendimiento Tri−Seal Completo',
      resPhoto: 'Tri−Sealseries.png',
      resHP: 2
   }
]

Advertisements