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
  • 46,070
  • 7
  • 44
  • 60
VVK
  • 405
  • 2
  • 18

1 Answers1

2

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
  • 46,070
  • 7
  • 44
  • 60