将每个数组项的出现次数和 return 结果作为一个对象进行计数

Count each array item occurrence and return result as an object

任何原生替代品来自:

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

至:

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

在 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);
这是我尝试实现的,但我想要一个已经内置的本机解决方案。

感谢您付出宝贵的努力和时间!!

Array.prototype.reduce() 似乎与您要查找的内容非常接近:

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%;}

使用.reduce:

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

let colorCount = colorArray.reduce((a, c) => ({ ...a, [c]: a[c] + 1 || 1}), {} );
      
console.log(colorCount);