Reputation: 615
I got to count how many times the elements are repeating, but I dont know how remove the repeated elements and add the counter just leaving one, example:
const list = [
{name:'A', count: 3 },
{name:'B', count: 2 },
{name:'C', count: 1 }
]
const list = [
{ id:1, name:'A' },
{ id:2, name:'B' },
{ id:3, name:'A' },
{ id:4, name:'A' },
{ id:5, name:'B' },
{ id:6, name:'C' }
]
let current = null;
let counter = 0;
for (var i = 0; i < list.length; i++) {
if (list[i] != current) {
current = list[i];
counter = 1;
} else {
counter += 1;
}
}
Upvotes: 1
Views: 83
Reputation: 501
const list = [
{ id:1, name:'A' },
{ id:2, name:'B' },
{ id:3, name:'A' },
{ id:4, name:'A' },
{ id:5, name:'B' },
{ id:6, name:'C' }
]
//First, get all the names:
const listNames = Array.from(new Set(list.map(item => item.name)))
console.log(listNames)
//Second, for each name, get the count and save to a new list:
const newList = []
listNames.forEach(name => {
const count = list.filter(item => item.name === name).length
newList.push({ name, count })
})
console.log(newList)
Upvotes: 0
Reputation: 3731
basically you can achieve this using Reduce to create the new array and inside of it with some logic and the use of finIndex you can fill your array.
this way is more easy than using nested loops or convert the data from one type to another.
const list = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'A' },
{ id: 4, name: 'A' },
{ id: 5, name: 'B' },
{ id: 6, name: 'C' }
]
const reducer = (accum, currentValue) => {
const name = currentValue.name;
// we look for the index of value in the accumulated array.
const index = accum.findIndex(entry => entry.name === name);
// if the index is different than -1 it is repeated, otherwise we have to add it.
if (index !== -1) {
accum[index].count += 1;
} else {
accum.push({
name: name,
count: 1
})
}
return accum;
}
const result = list.reduce(reducer, []);
console.log(result);
Upvotes: 0
Reputation: 2187
So you need to iterate over the array and then summate the count of the items. Using some of the ES6 array methods in javascript this is quite easy to do.
const list = [
{ id:1, name:'A' },
{ id:2, name:'B' },
{ id:3, name:'A' },
{ id:4, name:'A' },
{ id:5, name:'B' },
{ id:6, name:'C' }
];
// Create a mapping of name -> count
const mappedListCount = list.reduce((acc, { name, }) => {
acc[name] = acc[name] ? acc[name] + 1 : 1; // Increment count
return acc;
}, {});
// Convert the mapping to an array of { name, count }
const listCount = Object.entries(mappedListCount).map(([name, count]) => ({ name, count }));
console.log(listCount);
Upvotes: 1