繁体   English   中英

根据另一个数组中的值对数组进行排序-Javascript

[英]Sort array based on values in another array - Javascript

我有以下对象数组:

arr1 =  [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}]

arr2 =   [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]

如何根据arr1标题的值对arr2进行排序?

所需的输出将是:

[{Name: "ABC"}, {Name: "123"}, {Name: "XYZ"}]

您可以使用内置的sort方法并使用findIndex() 并且sort()基于该索引。 我使用了一个通用函数func来获取两个参数的索引。

 const arr1 = [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}] const arr2 = [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}]; const func = a => arr1.findIndex(b => b.chart.title === a.Name); const res = [...arr2].sort((a,b) => func(a) - func(b)); console.log(res) 

而不是对arr2进行排序,而是根据arr1中的值为其分配新值:

[{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}].map(item => ({"Name" : item.chart.title }) );

您可以使用Map作为索引。

 var array1 = [{ chart: { field: "test", title: "ABC", type: 0 } }, { chart: { field: "test", title: "123", type: 1 } }, { chart: { field: "test", title: "XYZ", type: 2 } }], array2 = [{ Name: "XYZ" }, { Name: "ABC" }, { Name: "123" }], indices = new Map(array1.map(({ chart: { title }}, i) => [title, i])); array2.sort(({ Name: a }, { Name: b }) => indices.get(a) - indices.get(b)); console.log(array2); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

只需从arr1创建一个新的arr2数组。

arr2 = arr1.map((result) => ({Name: result.chart.title}));

谢谢。

尝试以下解决方案

 arr1 = [{chart: {field: "test", title: "ABC", type: 0}}, {chart: {field: "test", title: "123", type: 1}}, {chart: {field: "test", title: "XYZ", type: 2}}] arr2 = [{Name: "XYZ"}, {Name: "ABC"}, {Name: "123"}] var newArr = []; arr1.filter(item=>{ newArr.push(arr2.find(element => element.Name === item.chart.title)); }); console.log(newArr); 

暂无
暂无

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

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