统计数组中的重复数据的数量
开发项目时,进行 行列合并时需要计算当前某值的出现次数,从而决定合并的行数,在搜集资料以及思考下做出如下总结
1、方法1
首先定义一个数组和空对象
const arr = ['a', 'b', 'c', 'a', 'a', 'b', '']; let obj = {}
循环数组,把循环的数据定义为属性名,倘若未找到相关属性值,默认传1, 否则在原有的数字上加1
arr.forEach(item => { obj[item] = (obj[item] + 1) || 1 }) console.log(obj)
打印obj内容如下
2、方法2
首先定义一个数组
const arr = ['a', 'b', 'c', 'a', 'a', 'b', ''];
对array.reduce 中的prev 赋值即可
reduce 的第一个参数得到的是迭代计算后的效果,所以可以使用第一个参数实现简单的数组去重和排序等arr.reduce(function(prev, next){ prev[next] = (prev[next] + 1) || 1; console.log( prev) },{});
打印prev内容如下:
3、方法3
简写reduce
let counts = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); console.log('数组counts中"李"出现的次数是:'+counts(["李","李","设","弟","弟","生","生","李"],"李"));
- 输出结果为
```
结果:数组counts中"李"出现的次数是:3
```
4、方法4
- 不用reduce时:
var arr = ["李","李","设","弟","弟","生","生","李"]; function getRepeatNum(){ var obj = {}; for(var i= 0, l = arr.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } console.log(getRepeatNum());
- 结果:{李: 3, 设: 1, 弟: 2, 生: 2}
5、方法5
- 用reduce时
var arr = ["李","李","设","弟","弟","生","生","李"]; function getRepeatNum(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getRepeatNum());
- 结果:{李: 3, 设: 1, 弟: 2, 生: 2}