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

后端 未结 3 1657
终归单人心
终归单人心 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:40

    You can use Map,

    • initialize hash as Map
    • Loop through array, if key is already present in hash increase it's value by 1 else set it to 1

    let arr = [1, 0, 0, 0, 1, 0, 0, 1]
    let hash = new Map()
    
    arr.forEach(val => {
      hash.set(val, (hash.get(val) || 0) + 1)
    })
    
    console.log([...hash])

提交回复
热议问题