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 ?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With