简体   繁体   中英

Sorting Js Array according to pre-defined array of indexes

hope you can help me fix this.

So I have one array with nested arrays:

mainArr: [[Carl, 20, Male],[Mike, 30, Male], [Chloe, 45, Female], ...]

Now this array needs to be sorted along another array containing a set order of indexes from the array above.

indexArr: [2,1,3,...]

Result here being:

sortedArr: [[Mike, 30, Male], [Carl, 20, Male], [Chloe, 45, Female], ...]

I thought about writing a ForEach loop with the second array, something along the lines of:

indexArr.forEach(i){
 sortedArr.push(mainArr[indexArr[i]]);
};

But I'm trying to avoid using loops with this function to keep it fast. I couldn't find anything relevant to my problem in any array documentation. Do you know a way to fill sortedArr or sort mainArr efficiently?

    indexArr.map(ind => mainArr[ind - 1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM