Last active
April 13, 2018 06:03
-
-
Save ruter/4281eea08be922c9574932352e4b7227 to your computer and use it in GitHub Desktop.
使用 reduce 统计一个数组中各个元素出现的次数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [4, 5, 3, 1, 6, 3, 4, 1] | |
let res = arr.reduce((countObj, ele) => { | |
if (ele in countObj) { | |
countObj[ele]++; | |
} else { | |
countObj[ele] = 1; | |
} | |
return countObj; | |
}, {}); | |
// res: {1: 2, 3: 2, 4: 2, 5: 1, 6: 1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment