Angular/Javascript合并具有条件的数组元素



我想合并2个数组元素以避免重复值

array = [
{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}
];

输出应为

result = [{id: 1, name:'abc OR xyz'},{id: 2, name:'text1 OR text2'}];

如果id相同,则名称字符串应与OR连接。如何使用Angular或javascript函数来完成此操作?我可以使用array.reduce((函数吗?如果是,我该怎么做?还是我只需要使用for循环?

您可以使用Array.reduce()id对项目进行分组。

这为每个id创建了一个具有属性的对象,然后我们可以使用Object.values()将结果作为数组。

const array = [{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}];
const result = Object.values(array.reduce((acc, { id, name }) => { 
if (!acc[id]) {
// Create a new entry in our map...
acc[id] = { id, name };
} else { 
// Append to the existing entry in our map...
acc[id].name += ' OR ' + name;
}
return acc;
}, {}))
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

您也可以使用for...of循环来获得相同的结果:

const array = [{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}];
const map = {};
for(let { id, name } of array) {
if (!map[id]) { 
map[id] = { id, name };
} else { 
map[id].name += ' OR ' + name;
}
}
const result = Object.values(map);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

这很容易做到。你以前试过什么?实现这一点有多种方法。

以下是我为帮助您而编写的一些快速伪代码:

result = []
idsFound = []
//Go over all elements in input array
for x = 0, x < array.length, x++
element = array[x]

//Id was already handled
if idsFound.indexOf(element.id) !== -1:
continue

//Go over all upcoming elements
for y = x + 1, y < array.length, y++
other_element = array[y]

//Check if id matches
if other_element.id === element.id:
//Append name
element.name += ' OR ' + other_element.name

//Push element and id
result.push(element)
idsFound.push(element.id)

最新更新