简体   繁体   中英

Sort array based on values in another array - Javascript

I have the following array of objects:

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"}]

How can I sort arr2 based on the value of the title of arr1?

The desired output would be:

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

You can use built-in sort method and use findIndex() . And sort() bases upon that index. I used a common function func for getting index of both arguments of sort.

 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 }) );

You could take a Map for the indices.

 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; } 

Just create a new array of arr2 from the arr1..

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

Thanks.

Try below solution

 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); 

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