js the number of each number calculated from the array

topic

'use strict';

var grouping_count = require("../../main/filter/grouping_count.js");

describe('grouping_count', function() {

  var collection = [1,1,1,1,2,3,1,3,4,2,3,1,3,4,2];

  it('从collection中计算出每个数的个数', function() {
    var result = grouping_count(collection);

    expect(result).toEqual({'1':6, '2':3, '3':4, '4':2});
  })
});

answer

'use strict';

function grouping_count(collection) {

  //在这里写入代码
	var res = {};
	collection.forEach(function(e){
    res[e] = res[e]>=1?res[e]+1:1
});
return res;

}

module.exports = grouping_count;

forEach () method calls for each element of the array, and passed to the callback function element.
can not read it

Guess you like

Origin blog.csdn.net/weixin_44769592/article/details/90974119