2

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"}]
2
  • What is the expected output? Commented Apr 17, 2019 at 13:40
  • You can sort the second array by finding the position of the element in the first array by the Name == title, and compare the positions in the sort method Commented Apr 17, 2019 at 13:43

5 Answers 5

4

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)

Sign up to request clarification or add additional context in comments.

Comments

2

Instead of sorting arr2 assign new value to it based on values in 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 }) );

Comments

0

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

Comments

-1

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

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

Thanks.

1 Comment

why negative marked? the answer below is the same as mine
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.