0

Sort one array based on another array when second array is the key in first array. Lets say I have a main array like below:

let mainArray = [{ "id": 24443, "name": "Apple" }, { "id": 20172, "name": "Banana" }, { "id": 187016, "name": "Cherry" }, { "id": 217632, "name": "Guava" }, { "id": 5221, "name": "Peach" }, { "id": 97568, "name": "Strawberry" }]

And I have id array like below:

let idArray = [ "24443", "20172", "5221", "187016", "217632", "97568" ]

Notice that second array contains values which are "id" property in the first array.

What are the best ways to sort the main array based on the order of occurrence of "key" in the second array?

0

2 Answers 2

1

If you are not absolutely after performance, here is a simple way of doing it:

mainArray.sort( (a,b) => idArray.indexOf(a.id.toString()) - idArray.indexOf(b.id.toString()));

Or for linear algorithm (parse both vectors only once):

// Array to Map
let map = mainArray.reduce( (acc, {id,name}) => Object.assign(acc, {[id] : name}), {});
idArray.map( id => ({id, name: map[id]}) )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate. Well I am using this in React with large lists;
0

I have created a function that does map and sorting: This function will map through the array of keys and find that key in the mainArray and return it.

var mapAndSort = (mainArr, indexArr, key) => {
    if (mainArr.length != indexArr.length) {
        return null;
    }
    return indexArr.map(val => {
        return mainArr.find(c => c[key] == val);
    });
}
var mainArray = [{ "id": 24443, "name": "Apple" }, { "id": 20172, "name": "Banana" }, { "id": 187016, "name": "Cherry" }, { "id": 217632, "name": "Guava" }, { "id": 5221, "name": "Peach" }, { "id": 97568, "name": "Strawberry" }];


var idArray = [  "20172","24443", "5221",  "217632", "97568", "187016"];

var result = mapAndSort(mainArray, idArray, 'id');

document.write(JSON.stringify(result));

3 Comments

You might consider leaving off the i parameter, since it's not used
True @CertainPerformance. :-)
Yeah, .find on each element is not efficient. See my answer for best performance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.