欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js计算数组中某个元素重复出现的个数

程序员文章站 2022-05-15 12:38:38
...

文章转载自https://blog.csdn.net/lixiaoyan93/article/details/88719333

1、计算特定值的重复个数

let counts = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
 
console.log('数组counts中"李"出现的次数是:'+counts(["李","李","设","弟","弟","生","生","李"],"李"));

结果:数组counts中"李"出现的次数是:3

2、计算数组中每个元素的重复个数

// 不用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}

// 用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}

相关标签: JS 方法