简体   繁体   English

根据存储位置的另一个数组对数组进行排序

[英]Sort an array based on another array that stores the position

I want to sort an based on another array that stores the position.我想根据存储位置的另一个数组对 an 进行排序。 They have in common groupName.他们有共同的组名。 For example:例如:

array1 = [ {groupName: "test", position: 0}, {groupName: "test2", position: 1}]

array2 = [ {groupName: "test2, otherValue: 10}, {groupName: "test", otherValue: 20}]

At the end I want to get the data from the second array but with the right positions: array = [{groupName: "test", otherValue: 20}, {groupName: "test2", otherValue: 10}]最后我想从第二个数组中获取数据,但位置正确: array = [{groupName: "test", otherValue: 20}, {groupName: "test2", otherValue: 10}]

You need to use .sort but for each item you compare you need to get the position from the other array.您需要使用.sort但对于您比较的每个项目,您需要从另一个数组中获取位置。

So所以

 const array1 = [{ groupName: "test", position: 0 }, { groupName: "test2", position: 1 }] const array2 = [{ groupName: "test2", otherValue: 10 }, { groupName: "test", otherValue: 20 }] const array = array2.slice().sort((a, b) => { const posA = array1.find(({ groupName }) => groupName === a.groupName).position; const posB = array1.find(({ groupName }) => groupName === b.groupName).position; return posA-posB; }); console.log(array);


Now if that was a huge array, you might want to cache the position to avoid searching for each compare现在,如果那是一个巨大的数组,您可能希望缓存该位置以避免搜索每个比较

 const array1 = [{ groupName: "test", position: 0 }, { groupName: "test2", position: 1 }] const array2 = [{ groupName: "test2", otherValue: 10 }, { groupName: "test", otherValue: 20 }] const positions = array1.reduce((acc, item) => ({...acc, [item.groupName]: item.position }), {}); const array = array2.slice().sort((a, b) => { return positions[a.groupName] - positions[b.groupName]; }); console.log(array);

 let arr1 = [{ groupName: "test", position: 0 }, { groupName: "test2", position: 1 }] let arr2 = [{ groupName: "test2", otherValue: 10 }, { groupName: "test", otherValue: 20 }]; let output = []; arr1.map((e, i, arr) => { let value = arr2.find(j => j.groupName === e.groupName); output.push(value); }) console.log(output);

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

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