简体   繁体   English

根据预定义的索引数组对 Js 数组进行排序

[英]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:我想用第二个数组编写一个 ForEach 循环,大致如下:

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?你知道一种有效地填充 sortedArr 或排序 mainArr 的方法吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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