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.

0

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.