2

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.

1

2 Answers 2

4

You can accomplish this succintly using reduce:

const input = [4,5,5,4,5,3,3,5,4,3];

const output = input.reduce((accum, x) => {
  accum[x] = accum[x] ? accum[x] + 1 : 1;
  return accum;
}, {});

console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.