Issue
Hey so i have one array with data like this
arr1 = [
{mood: "good", name: "Jake"},
{mood: "good", name: "Jill"},
{mood: "good", name: "Jack"}
]
and another array
arr2 = [
{number: 2, name: "Jake"},
{number: 1, name: "Jill"},
{number: 3, name: "Jack"}
]
I was looking to sort array one using the number from array 2. So, basically I would need to use a filter to match the name from arr1 to arr2 and then get the number from the resulting array and sort.
How can I get this done ?
arr1.sort((a: any, b: any) => arr1.filter((item: { name: string; }) => item.name == arr2[i].name));
I am totally lost, so much so, I may not have asked a proper question !
Solution
You could simply use an object for the order of name and take the value for sorting.
const
arr1 = [{ mood: "good", name: "Jake" }, { mood: "good", name: "Jill" }, { mood: "good", name: "Jack" }],
arr2 = [{ number: 2, name: "Jake" }, { number: 1, name: "Jill" }, { number: 3, name: "Jack" }],
order = Object.fromEntries(arr2.map(({ name, number }) => [name, number]));
arr1.sort((a, b) => order[a.name] - order[b.name]);
console.log(arr1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sorting by index. arr2
has a different order than above.
const
arr1 = [{ mood: "good", name: "Jake" }, { mood: "good", name: "Jill" }, { mood: "good", name: "Jack" }],
arr2 = [{ number: 1, name: "Jill" }, { number: 2, name: "Jake" }, { number: 3, name: "Jack" }],
order = Object.fromEntries(arr2.map(({ name }, index) => [name, index + 1]));
arr1.sort((a, b) => order[a.name] - order[b.name]);
console.log(arr1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answered By - Nina Scholz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.