say I have an array of objects below
const testObjects = [{ name: 'object1', detail1: 'detail', number: '25', detail2: ''},{ name: 'object2', detail1: 'detail', number: '5', detail2: '' },{ name: 'object3', detail1: 'detail', number: '19', detail2: '' },{ name: 'object4', detail1: 'detail', number: '38', detail2: '' },{ name: 'object1', detail1: 'detail', number: '12', detail2: 'some other detail'},{ name: 'object3', detail1: '', number: '71', detail2: 'detail' },];
I need to sort it a way that if the same name is matched in that array then it will return a new array of objects having both values. Like below
const finalObjects=[{ name: 'object1', detail1: 'detail', number: ['25','12'], detail2: 'some other detail' },
{ name: 'object2', detail1: 'detail', number: '5', detail2: '' },
{ name: 'object3', detail1: 'detail', number: ['19','71'], detail2: 'detail' },
{ name: 'object4', detail1: 'detail', number: '38', detail2: '' },]
CodePudding user response:
You can easily resolve this using Set
const seen = new Set();
const arr = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 2, name: "test3" },
{ id: 3, name: "test4" },
{ id: 4, name: "test5" },
{ id: 5, name: "test6" },
{ id: 5, name: "test7" },
{ id: 6, name: "test8" }
];
const filteredArr = arr.filter(el => {
const duplicate = seen.has(el.id);
seen.add(el.id);
return !duplicate;
});
CodePudding user response:
you need this right?:
let seen = new Map();
const arr = [
{ id: 1, name: "test1" },
{ id: 2, name: "test2" },
{ id: 1, name: "test1", attribute: "Something" },
{ id: 3, name: "test4" },
{ id: 4, name: "test5" },
{ id: 5, name: "test6" },
{ id: 5, name: "test7" },
{ id: 6, name: "test8" }
];
const filteredArr = [];
arr.forEach(element => {
const duplicate = seen.get(element.name);
if (duplicate) {
const currentKeys = Object.keys(element);
currentKeys.forEach(key => {
if (duplicate[key] === undefined) {
duplicate[key] = element[key]
}
})
seen.set(element.name, duplicate)
} else {
seen.set(element.name, element)
}
})
seen.forEach((value, name) => filteredArr.push(value));
console.log(filteredArr)