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

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) —
推荐阅读:全新认识冬季当家菜大白菜的营养价值 那些被人们误传的补充某种营养的食物 阿胶产品乱象:原料中被混入骡皮马皮 时令水果橘子橙子柚子营养价值大比拼 中医食疗:滋阴固肾的6款经典补粥 美味鸭肉的保健功效与养生食用方法 让枸杞中的营养成分吸收更好的吃法 多吃葱蒜少吃腌制食品防止胃病癌变 能够给肠道进行清洁排毒的常见食物 饮水养生:喝蜂蜜水的两个最佳时间
- 评论列表
-
- 添加评论