0

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?

3
  • 1
    What is the logic behind the sort? Commented Jun 19, 2017 at 16:42
  • 1
    Why is names an array, and what should happen when it contains more or less than exactly one item? Commented Jun 19, 2017 at 16:46
  • How to handle {id:999,names:['app', 'bootstrap']}? Commented Jun 19, 2017 at 16:47

3 Answers 3

1

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

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

2 Comments

Can someone explain to me how this works? What is the "delat of indices"?
@Michael, it should read delta, that is the difference between two values of a same group.
1

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

1 Comment

This is what I came up with at the beginning, but @NinaScholz way is so much cleaner!
1

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

2 Comments

Nice approach, but you'll want to mention that this only works when there's exactly one chunk per name.
True, I didn't take that into consideration. Thankfully there are more discerning eyes on SO than myself :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.