Issue
I want to merge 2 array elements to avoid duplicate values
array = [
{id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'}
];
Output should be
result = [{id: 1, name:'abc OR xyz'},{id: 2, name:'text1 OR text2'}];
If ids are the same then name strings should be concatenated with OR. How can i do this using Angular or javascript function? Can i do this using array.reduce() function? if yes how can i do that? Or do i need to use for loop only?
Solution
You can use Array.reduce()
to group the items by id
.
This creates an object with a property for each id, we can then use Object.values()
to get the result as an array.
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; }
You can also use a for...of
loop to get the same result:
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; }
Answered By - Terry Lennox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.