Javascript – Sort Array of objects by 2 Properties

You could use 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.

var array = [{ 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 }];

array.sort(function (a, b) {
    return a.resHP - b.resHP || b.resFlow - a.resFlow;
});

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

Leave a Comment