Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort fixed array of objects by using another array [duplicate]

I have variable that defines the order of objects like this:

const order = ['large', 'medium', 'small'];

I want to match that order of data array objects using names from order array:

const data = [{name: "small", children: []}, {name: "medium", children: []}, {name: "large", children: []}]

so the effect should be following:

const data = [{name: "large", children: []}, {name: "medium", children: []}, {name: "small", children: []}]

How can I achieve this ?

like image 777
Michał Lach Avatar asked Apr 22 '26 18:04

Michał Lach


1 Answers

We can do this by using the index of the name in the order array:

const order = ['large', 'medium', 'small'];
const data = [{name: "small", children: []}, {name: "medium", children: []}, {name: "large", children: []}];

const sortArray = (arr, order) => {
  return data.sort((a, b) => order.indexOf(a.name) - order.indexOf(b.name)); 
}
console.log(sortArray(data, order));
like image 115
Fullstack Guy Avatar answered May 01 '26 01:05

Fullstack Guy