I want to calculate number of unique value and put that in new array. I have below array:
[
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
{ CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]
I want new array with below result:
[
{ CategoryId: "b5c3f43f941c", count: 2, CategoryColor: "cgreen" }
{ CategoryId: "9872cce5af92", count: 1, CategoryColor: "purple" }
]
In this check by id, if id is same show count and new in new array.
Hope you understand what I want.
Thanks,
You can loop through array using "for..of" and create a temporary object to save data in every loop. If same id exists in tempObject then increment count by 1
var arr = [
{ CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
, { CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }
, { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }
]
var tempResult = {}
for(let { CategoryColor, CategoryId } of arr)
tempResult[CategoryId] = {
CategoryId,
CategoryColor,
count: tempResult[CategoryId] ? tempResult[CategoryId].count + 1 : 1
}
let result = Object.values(tempResult)
console.log(result)
Use reduce function and inside the callback check an object exist whose CategoryId matches. If matches then update the count or else create a new object with the values and push in the array
let k = [{
CategoryId: "b5c3f43f941c",
CategoryName: "Category 1",
CategoryColor: "cgreen"
},
{
CategoryId: "9872cce5af92",
CategoryName: "Category 2",
CategoryColor: "purple"
},
{
CategoryId: "b5c3f43f941c",
CategoryName: "Category 1",
CategoryColor: "cgreen"
}
]
let result = k.reduce(function(acc, curr) {
// Check if there exist an object in empty array whose CategoryId matches
let isElemExist = acc.findIndex(function(item) {
return item.CategoryId === curr.CategoryId;
})
if (isElemExist === -1) {
let obj = {};
obj.CategoryId = curr.CategoryId;
obj.count = 1;
obj.CategoryColor = curr.CategoryColor;
acc.push(obj)
} else {
acc[isElemExist].count += 1
}
return acc;
}, [])
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With