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?

Abhay Shiro
  • 3,431
  • 2
  • 16
  • 26

2 Answers2

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]}) )
RaphaMex
  • 2,781
  • 1
  • 14
  • 30
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));
Abhay Shiro
  • 3,431
  • 2
  • 16
  • 26