I have an array which has different location and items.
[
{"location": "north", "items" : ["IT1", "IT2"]},
{"location": "south", "items" : ["IT1", "IT2"]},
{"location": "north", "items" : ["IT3", "IT4"]}
]
I want to remove duplicate location fields and append the items property from the duplicate to achieve this:
[
{"location": "north", "items" : ["IT1", "IT2", "IT3", "IT4"]},
{"location": "south", "items" : ["IT1", "IT2"]}
]
How can I do it with vanilla JS?
By adapting How to group or merge this array of objects in javascript? to accumulate arrays instead of numbers, here's the result:
var arr = [{
"location": "north",
"items": ["IT1", "IT2"]
},
{
"location": "south",
"items": ["IT1", "IT2"]
},
{
"location": "north",
"items": ["IT3", "IT4"]
}
];
var finalArr = arr.reduce((m, o) => {
var found = m.find(p => p.location === o.location);
if (found) {
found.items = found.items.concat(o.items);
} else {
m.push(o);
}
return m;
}, []);
console.log(finalArr)
I hope it would work for you
var data = [
{"location": "north", "items" : ["IT1", "IT2"]},
{"location": "south", "items" : ["IT1", "IT2"]},
{"location": "north", "items" : ["IT3", "IT4"]}
];
const result = data.filter((thing, index, self) =>
index === self.findIndex((t) => (
t.location === thing.location
))
)
console.log(result);
Build an object with keys as location and values as aggregated items.
const process = (arr, track = {}) => {
arr.forEach((obj) => {
if (track[obj.location]) {
track[obj.location] = {
...track[obj.location],
items: obj.items.concat(track[obj.location].items),
};
} else {
track[obj.location] = { ...obj };
}
});
return Object.values(track);
};
const data = [
{ location: "north", items: ["IT1", "IT2"] },
{ location: "south", items: ["IT1", "IT2"] },
{ location: "north", items: ["IT3", "IT4"] },
];
console.log(process(data));