Using Reduce to Count the Array in Javascript

  • 时间:2020-09-24 11:54:15
  • 分类:网络文摘
  • 阅读:103 次
JS Using Reduce to Count the Array in Javascript javascript

NodeJs / Javascript

Let’s say, we have an array in Javascript, and we want to group the elements, ount their occurences and store the final results in a key-value dictionary.

Input Array:

1
const cars = ['BMW', 'Audi', 'Audi', 'Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
const cars = ['BMW', 'Audi', 'Audi', 'Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];

Output JSON-like key-value pairs i.e. mapping:

{ BMW: 2, Audi: 2, Benz: 2, Tesla: 1, Toyota: 1 }

We can add a functoin count by extending the Array’s prototype. We will implement it using the Array’s reduce the array into a single value. The reduce takes two parameters, the first one is the function(previousValue, currentValue, currentIndex, currentArray), and the second value is the initial value.

1
2
3
4
5
6
Array.prototype.count = function() {
    return this.reduce(function(obj, name) {
        obj[name] = obj[name] ? ++obj[name] : 1;
        return obj;
    }, {});
}
Array.prototype.count = function() {
    return this.reduce(function(obj, name) {
        obj[name] = obj[name] ? ++obj[name] : 1;
        return obj;
    }, {});
}

We pass the initial value, {} i.e. an empty JSON-object, then in the reduced-function, we will update the frequency of the current element in the dictionary and return the updated object for next iteration.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
申请百度联盟,几次三番都不成功啊!  新浪sae不支持写操作,需要移植代码!  维生素B2(核黄素)的食物来源  维生素B1(硫胺素)的食物来源  公众最担心食品添加有毒有害物质  食品安全蓝皮书发布 解读2012食品问题  购买保健食品要认准“蓝帽子”标志  食品安全问题公众和媒体也有话语权  初春食补:胡椒根对症食疗祛除寒湿  纯天然食品与绿色食品有何区别 
评论列表
添加评论