Skip to content

Instantly share code, notes, and snippets.

@ruter
Last active April 13, 2018 06:03
Show Gist options
  • Save ruter/4281eea08be922c9574932352e4b7227 to your computer and use it in GitHub Desktop.
Save ruter/4281eea08be922c9574932352e4b7227 to your computer and use it in GitHub Desktop.
使用 reduce 统计一个数组中各个元素出现的次数
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