我尝试将这两个对象数组组合在一起,并获得以下输出。userid
属性应该是唯一的,但不是name
或role
输入
const first = [
{ userid: 2, name: "Velen" },
{ userid: 56, name: "Illidan" },
{ userid: 23, name: "Muradin" },
{ userid: 12, name: "Sylvanas" },
{ userid: 44, name: "Cenarius" },
{ userid: 4, name: "Gul'Dan" },
];
const second = [
{ userid: 2, role: "Mage" },
{ userid: 4, role: "Worlock" },
{ userid: 56, role: "Demon Hunter" },
{ userid: 66, role: "Druid" },
{ userid: 87, role: "Shaman" },
{ userid: 12, role: "Hunter" },
];
产出
[
{ name: 'Velen', role: 'Mage', userid: 2 },
{ name: "Gul'Dan", role: 'Worlock', userid: 4 },
{ name: 'Sylvanas', role: 'Hunter', userid: 12 },
{ name: 'Muradin', role: null, userid: 23 },
{ name: 'Cenarius', role: null, userid: 44 },
{ name: 'Illidan', role: 'Demon Hunter', userid: 56 },
{ name: null, role: 'Druid', userid: 66 },
{ name: null, role: 'Shaman', userid: 87 }
]
我尝试了这个解决方案,但它不工作:
const solution = (first, second) => {
first.sort((a, b) => a.userid - b.userid);
second.sort((a, b) => a.userid - b.userid);
first.map((item, idx) => {
return {
a: (item.role = second[idx].role),
b: (item.userid = second[idx].userid),
};
});
return first;
};
console.log(solution(first, second));
4条答案
按热度按时间uqcuzwp81#
你可以用一个对象来减少,并使用一个默认的对象来使值无效。
ekqde3dh2#
在这种情况下,通常使用Maps/Dictionary/(key/value)数据结构是很好的,这里key是用户标识,value是你想要存储的属性。
最后,我们使用userid排序,就像你尝试做的那样,没有排序,解的时间复杂度是
O(n)
,有排序,解的时间复杂度是O(n*log(n))
。zwghvu4y3#
这是我能想到的使用reduce的最好方法,不得不使用其中的两个来达到想要的结果。假设第一个数组总是包含
userid
和name
,而第二个数组总是包含userid
和role
。vql8enpb4#
您可以使用
reduce
函数执行此操作,如下所示: