Reputation: 5283
So let's say I have an array:
const chunks = [
{id: 0, names: ['app']},
{id: 1, names: ['contact']},
{id: 2, names: ['bootstrap']}
];
And I want it to be sorted based on the names
property, so the order is like in this array:
const original = ['bootstrap', 'app', 'contact'];
What is the most efficient way to do this?
Upvotes: 0
Views: 310
Reputation: 386816
You could use the delta of the indices of names in original.
const chunks = [{ id: 0, names: ['app'] }, { id: 1, names: ['contact'] }, { id: 2, names: ['bootstrap'] }],
original = ['bootstrap', 'app', 'contact'];
chunks.sort((a, b) => original.indexOf(a.names[0]) - original.indexOf(b.names[0]));
console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 139
Easy way: convert chunks into an object so you get the correct one with just the key, then map over the (already sorted) array to plug in the object in place.
cMap = chunks.reduce((p,c) => Object.assign( p, {[c.names[0]]: c} ), {});
const sorted = original.map(k => cMap[k]);
Upvotes: 1
Reputation: 3470
Try this method:
const chunks = [{id: 0, names: ['app']}, {id: 1, names: ['contact']}, {id: 2, names: ['bootstrap']}];
const original = ['bootstrap', 'app', 'contact'];
let result = [];
for(let i = 0; i < original.length; i++) {
for(let j = 0; j < chunks.length; j++) {
if(chunks[j].names.indexOf(original[i]) !== -1) {
result.push(chunks[j]);
}
}
}
console.log(result);
Upvotes: 1