简体   繁体   中英

Stuck on creating a function that will return objects

Hi I was wondering if I can get some help here I am stuck. I am trying to create a histogram function that takes an array like ['a', 'a', 'b', 'c', 'b', 'a'] and returns {a:3, b:2, c:1} using the reduce function to build the histogram function. But I am stuck on what the callback function should be.


Thank you for any responses.

Try to iterate over the array and fill/increment the object's value accordingly,

var x = ['a', 'a', 'b', 'c', 'b', 'a'];
var y = {};

x.forEach(function(itm){
 y[itm] = ++y[itm] || 1;
});

You can reduce your array like this:

['a', 'a', 'b', 'c', 'b', 'a'].reduce(function(obj, value) {
    obj[value] = obj[value] || 0;
    obj[value]++;
    return obj; 
}, {});

If your environment supports Object.assign() and ES6 you can also do this:

['a', 'a', 'b', 'c', 'b', 'a']
    .reduce((a, b) => Object.assign(a, {[b]: a[b] ? ++a[b] : 1}), {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM