0

Let's say I have an array of objects:

let array = [

    {id: 0, type: "Office" },
    {id: 1, type: "Security" },
    {id: 2, type: "Office" },
    {id: 3, type: "Security" },
    {id: 4, type: "Security" },
    {id: 5, type: "Office" },
    {id: 6, type: "Agent" },
    {id: 7, type: "Security" }

];

I need to sort it according custom categorical sequence set, i.e. ["Office", "Agent", "Security"] to get the following output:

var array = [
    {id: 0, type: "Office" },
    {id: 2, type: "Office" },
    {id: 5, type: "Office" },
    {id: 6, type: "Agent" }
    {id: 1, type: "Security" },
    {id: 3, type: "Security" },
    {id: 4, type: "Security" },
    {id: 7, type: "Security" }
];

Didn't find any proper solution for that.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
VVK
  • 435
  • 2
  • 27

1 Answers1

3

You can use indexOf to get the sort order.

let array = [
    {id: 0, type: "Office" },
    {id: 1, type: "Security" },
    {id: 2, type: "Office" },
    {id: 3, type: "Security" },
    {id: 4, type: "Security" },
    {id: 5, type: "Office" },
    {id: 6, type: "Agent" },
    {id: 7, type: "Security" }
];
const order = ["Office", "Agent", "Security"]
array.sort((a,b)=>order.indexOf(a.type)-order.indexOf(b.type));
console.log(array);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80