【问题标题】:Count each array item occurrence and return result as an object [duplicate]计算每个数组项的出现并将结果作为对象返回[重复]
【发布时间】:2020-12-20 10:42:48
【问题描述】:

任何本地替代方案:

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

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

【问题讨论】:

    标签: javascript arrays duplicates categorical-data categorization


    【解决方案1】:

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

    【讨论】:

    • 不太明白 (acc,color) => (acc[color]=(acc[color]||0)+1, acc) 的工作原理。顺便说一句,我对减少、积累和当前的论点有一点经验。请解释一下。
    • @Jhon : 我相信是 shortcircuit OR evaluationcomma operator 让你感到困惑。
    • @Jhon :简而言之,acc[color]||0 被评估为 acc[color]0 如果前者是 undefined (第一次穿过每种特定颜色); (acc[color]=(acc[color]||0)+1, acc)acc[color] = acc[color]||0+1; return acc 基本相同
    • 小心comma-operator -&gt; no-sequences rule
    【解决方案2】:

    使用.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);

    【讨论】:

    • 这种方法的小问题是,当输入数组足够大时,它会在每次迭代时重新创建不必要的累加器对象may slow down 代码。
    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 2015-09-11
    • 2017-12-28
    • 2019-06-28
    • 2020-08-12
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    相关资源
    最近更新 更多