Search code examples
javascriptarraysduplicatescategorical-datacategorization

Count each array item occurrence and return result as an object


Any native alternatives for going from:

const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];

to:

Object {
  "red": 3,
  "green": 2,
  "blue": 1,
  "purple": 1,
  "black": 1
}

in javascript??

const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];

function categorizeUnique(array) {
  const distinct_objects = {};
  const length = array.length;
  for(let i=0; i<length; i++) {
    const distinct_objects_keys = Object.keys(distinct_objects);
    const possible_index = distinct_objects_keys.indexOf(array[i]);
    if(possible_index === -1) {
      distinct_objects[array[i]] = 1;
    } else {
      distinct_objects[distinct_objects_keys[possible_index]]++;
    }
  }
  return distinct_objects;
}

const result = categorizeUnique(colorArray);
console.log(result);
That was my try to accomplish this but I'd like a native solution already built in.

Thanks for your precious effort and time!!


Solution

  • Array.prototype.reduce() seems to be pretty close to what you're looking for:

    const src = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'],
    
          result = src.reduce((acc,color) => (acc[color]=(acc[color]||0)+1, acc), {})
          
    console.log(result)
    .as-console-wrapper{min-height:100%;}