Sort an array of object by a property (with custom order, not alphabetically)

You could take an object for the wanted order.

var array = [{ code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3 };
    
array.sort(function (a, b) {
    return order[a.code] - order[b.code];
});

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

For unknow colors/values, you could use a default value with

  • 0, for sorting to top or
  • Infinity or as some suggest because of the ability for caculating Number.MAX_VALUE for sorting to the end,
  • or any other value for sorting inbetween the other groups.

At last you could sort the special treated items with an other sorting part, chained with logical OR ||.

var array = [{ code: "YELLOW", value: 0 }, { code: "BLACK", value: 0 }, { code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3, default: Infinity };
    
array.sort(function (a, b) {
    return (order[a.code] || order.default) - (order[b.code] || order.default) || a.code.localeCompare(b.code);
});

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

Leave a Comment