JavaScript重复元素处理方法分析【统计个数、计算、去重复等】
在JavaScript中,处理重复元素是常见的需求,本篇文章将分析几种处理重复元素的方法,包括统计个数、计算、去重复等。
统计个数
统计重复元素的个数是最常见的需求,以下是一些实现方法:
方法1:for循环+计数器
let arr = ["apple", "banana", "apple", "grape", "banana"];
let count = {};
for(let i = 0; i < arr.length; i++){
if(!count[arr[i]]){
count[arr[i]] = 1;
}else{
count[arr[i]]++;
}
}
console.log(count); //{ apple: 2, banana: 2, grape: 1 }
方法2:foreach循环+计数器
let arr = ["apple", "banana", "apple", "grape", "banana"];
let count = {};
arr.forEach(function(item){
if(!count[item]){
count[item] = 1;
}else{
count[item]++;
}
})
console.log(count); //{ apple: 2, banana: 2, grape: 1 }
方法3:reduce方法
let arr = ["apple", "banana", "apple", "grape", "banana"];
let count = arr.reduce(function(pre, cur){
pre[cur] ? pre[cur]++ : pre[cur] = 1;
return pre;
}, {});
console.log(count); //{ apple: 2, banana: 2, grape: 1 }
计算
计算重复元素的总和、平均值等情况也是常见的需求,以下是一些实现方法:
方法1:for循环+计数器+计算器
let arr = [1, 3, 5, 5, 7, 9, 9];
let count = 0;
let sum = 0;
for(let i = 0; i < arr.length; i++){
count++;
sum += arr[i];
}
let avg = sum/count;
console.log(avg) //5.571428571428571
方法2:foreach循环+计数器+计算器
let arr = [1, 3, 5, 5, 7, 9, 9];
let count = 0;
let sum = 0;
arr.forEach(function(item){
count++;
sum += item;
})
let avg = sum/count;
console.log(avg) //5.571428571428571
方法3:reduce方法
let arr = [1, 3, 5, 5, 7, 9, 9];
let count = arr.length;
let sum = arr.reduce(function(pre, cur){
return pre + cur;
}, 0);
let avg = sum/count;
console.log(avg) //5.571428571428571
去重复
去重复也是常见的需求,以下是一些实现方法:
方法1:for循环+indexOf+新数组
let arr = ["apple", "banana", "apple", "grape", "banana"];
let newArr = [];
for(let i = 0; i < arr.length; i++){
if(newArr.indexOf(arr[i]) == -1){
newArr.push(arr[i]);
}
}
console.log(newArr); //["apple", "banana", "grape"]
方法2:forEach循环+includes+新数组
let arr = ["apple", "banana", "apple", "grape", "banana"];
let newArr = [];
arr.forEach(function(item){
if(!newArr.includes(item)){
newArr.push(item);
}
})
console.log(newArr); //["apple", "banana", "grape"]
方法3:Set数据结构
let arr = ["apple", "banana", "apple", "grape", "banana"];
let newArr = [...new Set(arr)];
console.log(newArr); //["apple", "banana", "grape"]
总结
以上是JavaScript中处理重复元素的一些实现方法,其中统计个数、计算和去重复都是常见的需求,选择哪种方法主要取决于具体场合和需求。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JavaScript重复元素处理方法分析【统计个数、计算、去重复等】 - Python技术站