this is my array of object.
const arr = [{"company":"Google","product":"A","sell":34},{"company":"Google","product":"B","sell":31},{"company":"Google","product":"C","sell":64},{"company":"Twitter","product":"A","sell":34},{"company":"Twitter","product":"B","sell":56},{"company":"Twitter","product":"C","sell":48}]
solution which i have tried.
const result = arr.reduce((acc, d) => {
const found = acc.find(a => a.name === d.name);
if (!found) {
acc.push({ name: d.name, [d.value]: d.count })
}
else {
found.push({ [d.value]: d.count });
}
return acc;
}, []);
console.log(result)
expected output should be like below but something wrong in else block
[{ company: "Google", A: 34, B:31, C:64 },{ company: "Twitter", A: 34, B:56, C:48 }]
You have property names wrong all over your code.
And yes, the else block should just create a new property found[d.product] = d.sell;
const arr = [{
"company": "Google",
"product": "A",
"sell": 34
}, {
"company": "Google",
"product": "B",
"sell": 31
}, {
"company": "Google",
"product": "C",
"sell": 64
}, {
"company": "Twitter",
"product": "A",
"sell": 34
}, {
"company": "Twitter",
"product": "B",
"sell": 56
}, {
"company": "Twitter",
"product": "C",
"sell": 48
}]
const result = arr.reduce((acc, d) => {
const found = acc.find(a => a.name === d.company);
if (!found) {
acc.push({
name: d.company,
[d.product]: d.sell
})
} else {
found[d.product] = d.sell;
}
return acc;
}, []);
console.log(result)
Other than that current algorithm is O(n^2) if you want it to be linear you could use Map to store data to avoid O(n) lookups
const arr = [{
"company": "Google",
"product": "A",
"sell": 34
}, {
"company": "Google",
"product": "B",
"sell": 31
}, {
"company": "Google",
"product": "C",
"sell": 64
}, {
"company": "Twitter",
"product": "A",
"sell": 34
}, {
"company": "Twitter",
"product": "B",
"sell": 56
}, {
"company": "Twitter",
"product": "C",
"sell": 48
}]
const result = [...arr.reduce((acc, d) => {
const found = acc.get(d.company); // O(1) lookup
if (found) {
found[d.product] = d.sell
} else {
acc.set(d.company, {
name: d.company,
[d.product]: d.sell
})
}
return acc
}, new Map).values()];
console.log(result)
const arr = [{ "company": "Google", "product": "A", "sell": 34 }, { "company": "Google", "product": "B", "sell": 31 }, { "company": "Google", "product": "C", "sell": 64 }, { "company": "Twitter", "product": "A", "sell": 34 }, { "company": "Twitter", "product": "B", "sell": 56 }, { "company": "Twitter", "product": "C", "sell": 48 }]
const res = []
arr.forEach(function (item) {
const idxExist = res.findIndex(el => el.company === item.company)
if (idxExist === -1) {
res.push({"company": item['company'], [item['product']]: item['sell']})
} else {
res[idxExist][item['product']] = item['sell']
}
})
console.log(res)