How do you count occurrences of an object in a javascript array, then associate this with the object. For example:
If my array is : [4,5,5,4,5,3,3,5,4,3]
How would I get a key/value pair that would count how many times the object occurred, and what object that is. So the output I am looking for is: {3:3, 4:3, 5:4} meaning 3 occurred 3 times, 4 occurred 3 times, and 5 occurred 4 times.
-
3Have you searched the archives for this? There are many existing answers. (i.e. stackoverflow.com/questions/5667888/…)Mark– Mark2019-02-04 21:34:49 +00:00Commented Feb 4, 2019 at 21:34
Add a comment
|
2 Answers
You can use Array.prototype.reduce() to iterate through the array. The accumulator in the function will be a plain object, {}, and in each iteration you simply check if the array's item is a key in the object or not:
- if it is not, then create a new key and give it a count of 1
- if it is, then access the pre-existing key and increment its count by 1
const arr = [4,5,5,4,5,3,3,5,4,3];
const keyedArr = arr.reduce((accumulator, currentValue) => {
const key = currentValue.toString();
if (!(key in accumulator))
accumulator[key] = 1;
else
accumulator[key] += 1;
return accumulator;
}, {});
console.log(keyedArr);