gpt4 book ai didi

javascript - 两个集合形成一个集合,用更新的字段替换重复项

转载 作者:行者123 更新时间:2023-11-28 15:01:45 25 4
gpt4 key购买 nike

我有两个独特的集合,看起来像这样:

集合一:

[
{
id: 123,
Name: Ben,
Type: Car
},
{
id: 124,
Name: Morgan,
Type: Van
},
{
id: 125,
Name: Josh,
Type: Bus
}
]

集合二:

[
{
id: 123,
Name: Ben,
Type: House
},
{
id: 124,
Name: Morgan,
Type: Flat
},
{
id: 126,
Name: Jack,
Type: Landrover
}
]

我已使用 lodash _.uinqBy 确保两个集合中没有重复项。

但是,我想将两者合并在一起以创建一个集合,但将具有匹配 id 的集合替换为类型为 === "Car"|| 的集合===“货车”

因此,我从上述集合中得到的结果将是:

结果:

[
{
id: 123,
Name: Ben,
Type: Car
},
{
id: 124,
Name: Morgan,
Type: Van
},
{
id: 125,
Name: Josh,
Type: Bus
},
{
id: 126,
Name: Jack,
Type: Landrover
}
]

无论如何,我可以使用 lodash 来做到这一点吗?或者有其他方式吗?

提前致谢:)

最佳答案

使用洛达什:

function unite(arr1, arr2) {
return _(arr1)
.concat(arr2) // concat the arrays
.groupBy('id') // create a group by the id
.map(function(group) { // in each group
return _.find(group, function(item) { // find if one contains the request Type, and if not return the 1st in the group
return item.Type === 'Car' || item.Type === 'Van';
}) || _.head(group);
})
.values() // exract the values
.value();
}

function unite(arr1, arr2) {
return _(arr1)
.concat(arr2) // concat the arrays
.groupBy('id') // create a group by the id
.map(function(group) { // in each group
return _.find(group, function(item) { // find if one contains the request Type, and if not return the 1st in the group
return item.Type === 'Car' || item.Type === 'Van';
}) || _.head(group);
})
.values() // exract the values
.value();
}

var arr1 = [{
id: '123',
Name: 'Ben',
Type: 'Car'
}, {
id: '124',
Name: 'Morgan',
Type: 'Flat'
}, {
id: '125',
Name: 'Josh',
Type: 'Bus'
}];

var arr2 = [{
id: '123',
Name: 'Ben',
Type: 'House'
}, {
id: '124',
Name: 'Morgan',
Type: 'Van'
}, {
id: '126',
Name: 'Jack',
Type: 'Landrover'
}];

var result = unite(arr1, arr2);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

使用 ES6 Map 和传播:

const uniqueUnion = (arr1, arr2) => [
...arr1.concat(arr2)
.reduce((m, item) => {
if(!m.has(item.id) || item.Type === 'Car' || item.Type === 'Van') {
m.set(item.id, item);
}

return m;
}, new Map()).values()
];

const unite = (arr1, arr2) => [
...arr1.concat(arr2)
.reduce((m, item) => {
if (!m.has(item.id) || item.Type === 'Car' || item.Type === 'Van') {
m.set(item.id, item);
}

return m;
}, new Map()).values()
];

const arr1 = [{
id: '123',
Name: 'Ben',
Type: 'Car'
}, {
id: '124',
Name: 'Morgan',
Type: 'Flat'
}, {
id: '125',
Name: 'Josh',
Type: 'Bus'
}];

const arr2 = [{
id: '123',
Name: 'Ben',
Type: 'House'
}, {
id: '124',
Name: 'Morgan',
Type: 'Van'
}, {
id: '126',
Name: 'Jack',
Type: 'Landrover'
}];

const result = unite(arr1, arr2);

console.log(result);

关于javascript - 两个集合形成一个集合,用更新的字段替换重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40637703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com