How to declare Hash.new(0) with 0 default value for counting objects in JavaScript?

后端 未结 3 1658
终归单人心
终归单人心 2021-01-24 11:48

I\'m trying to iterate through an array of digits and count how many times each digit is found in the array.

In ruby it\'s easy, I just declare a Hash.new(0)

3条回答
  •  故里飘歌
    2021-01-24 12:38

    In Javascript you do it with Array.reduce

    const reducer = (acc, e) => acc.set(e, (acc.get(e) || 0) + 1);
    [1, 0, 0, 0, 1, 0, 0, 1].reduce(reducer, new Map())
    //⇒ Map(2) {1 => 3, 0 => 5}
    

提交回复
热议问题