I have below array of objects,
var data = [
{
label: \"Book1\",
data: \"US edition\"
},
{
label: \"Book1\",
data:
I came across the same situation and I was hoping to use the Set
instead of mine here
const data = [
{
label: "Book1",
data: "US edition"
},
{
label: "Book1",
data: "UK edition"
},
{
label: "Book2",
data: "CAN edition"
},
{
label: "Book3",
data: "CAN edition"
},
{
label: "Book3",
data: "CANII edition"
}
];
const filteredArr = data.reduce((acc, current) => {
const x = acc.find(item => item.label === current.label);
if (!x) {
const newCurr = {
label: current.label,
data: [current.data]
}
return acc.concat([newCurr]);
} else {
const currData = x.data.filter(d => d === current.data);
if (!currData.length) {
const newData = x.data.push(current.data);
const newCurr = {
label: current.label,
data: newData
}
return acc;
} else {
return acc;
}
}
}, []);
console.log(filteredArr);