js 找出数组中‘globalNumber’值一样的并且大于2个的放在一个数组中
时间: 2024-12-13 13:16:06 浏览: 8
在JavaScript中,你可以使用`filter()`、`reduce()`或`Array.prototype.map()`等函数结合`Array.prototype.findIndex()`来找出数组中所有具有相同`globalNumber`值且数量大于2的元素。这里是一个示例:
```javascript
function filterDuplicates(array, globalNumberKey) {
// 使用filter和reduce找到有超过2个相同值的元素
const duplicates = array.reduce((acc, current) => {
const index = acc.findIndex(item => item[globalNumberKey] === current[globalNumberKey]);
if (index > -1) {
acc[index].push(current);
} else if (acc.length >= 2 && acc[acc.length - 1][globalNumberKey] === current[globalNumberKey]) {
acc[acc.length - 1].push(current);
} else {
acc.push([current]);
}
return acc;
}, []);
// 返回只包含重复值集合且长度大于2的结果
return duplicates.filter(group => group.length > 2);
}
// 示例数组
const numbers = [
{ globalNumber: 1, value: 'one' },
{ globalNumber: 2, value: 'two' },
{ globalNumber: 2, value: 'two' },
{ globalNumber: 3, value: 'three' },
{ globalNumber: 4, value: 'four' },
{ globalNumber: 2, value: 'two' },
];
const result = filterDuplicates(numbers, 'globalNumber');
console.log(result); // 结果是 [{ globalNumber: 2, value: ['two', 'two'] }]
阅读全文