有没有办法使用不同数组中的值进行排序

问题描述 投票:0回答:1

嘿,我有一个包含这样数据的数组

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

我希望使用数组 2 中的数字对数组 1 进行排序。因此,基本上我需要使用过滤器来匹配从 arr1 到 arr2 的名称,然后从结果数组中获取数字并进行排序。

我怎样才能完成这个工作?

arr1.sort((a: any, b: any) => arr1.filter((item: { name: string; }) => item.name == arr2[i].name));

我完全迷失了,以至于我可能没有问一个正确的问题!

javascript arrays typescript sorting
1个回答
0
投票

您可以创建一个查找函数来查找号码,如下所示:

const arr1 = [{"mood":"good","name":"Jake"},{"mood":"good","name":"Jill"},{"mood":"good","name":"Jack"}]
const arr2 = [{"number":2,"name":"Jake"},{"number":1,"name":"Jill"},{"number":3,"name":"Jack"}]

const f = o => arr2.find(({name}) => name===o.name).number

arr1.sort((a,b) => f(a) - f(b))

console.log(arr1)

© www.soinside.com 2019 - 2024. All rights reserved.