在JavaScript中计算数组中的重复值,可以通过多种方法实现。以下是几种常见的方法:
function countDuplicates(arr) {
const counts = {};
let duplicates = [];
arr.forEach(item => {
counts[item] = (counts[item] || 0) + 1;
});
for (const item in counts) {
if (counts[item] > 1) {
duplicates.push(item);
}
}
return duplicates;
}
// 示例
const array = [1, 2, 2, 3, 4, 4, 4, 5];
console.log(countDuplicates(array)); // 输出: [ '2', '4' ]
function countDuplicates(arr) {
const counts = new Map();
let duplicates = [];
arr.forEach(item => {
counts.set(item, (counts.get(item) || 0) + 1);
});
counts.forEach((count, item) => {
if (count > 1) {
duplicates.push(item);
}
});
return duplicates;
}
// 示例
const array = [1, 2, 2, 3, 4, 4, 4, 5];
console.log(countDuplicates(array)); // 输出: [ 2, 4 ]
function countDuplicates(arr) {
const counts = arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
return Object.keys(counts).filter(item => counts[item] > 1);
}
// 示例
const array = [1, 2, 2, 3, 4, 4, 4, 5];
console.log(countDuplicates(array)); // 输出: [ '2', '4' ]
这种方法可以用于各种需要统计数组中重复值的场景,例如:
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云