我有一个大数据阵列,我需要一种可靠的方法来提取适当的值以及实现重复数据删除一体化。
由于公平值被放入我的数组中,我需要从我的数组中提取至少发生5次或更多次的值......
这是我得到的:
var data=['1','1','1','1','1','1','1','5','5','5','5','6','7','7','7','7','7','7']
var uniqueArray = data.filter(function(elem, pos) {
return data.indexOf(elem) == pos;
});
for (var i=0; i<uniqueArray.length;i++){
console.log(uniqueArray);
};
当我尝试添加以下代码时,上面的代码正常运行以删除重复值:
var uniqueArray = data.filter(function(elem, pos) {
return data.indexOf((elem) == pos) > 5;
});
for (var i=0; i<uniqueArray.length;i++){
console.log(uniqueArray);
};
这不起作用......我没有收到任何价值。
我希望收到的新数组中只有1和7
Plz帮忙!
提前致谢!
答案 0 :(得分:2)
一个简单的解决方案是在下面的代码段中构建一个索引(名为counts
),表示数组中每个值的出现次数:
const data = ['1','1','1','1','1','1','1','5','5','5','5','6','7','7','7','7','7','7'];
const counts = data.reduce((result, value) => {
result[value] = (result[value] || 0) + 1;
return result;
}, {});
const result = Object.keys(counts).filter(value => counts[value] >= 5);
console.log(result);
或者,如果对数组进行了排序,则可以使用更加程序化的解决方案来消除对counts
对象的需求:
const data = ['1','1','1','1','1','1','1','5','5','5','5','6','7','7','7','7','7','7'];
let current;
let count = 0;
let result = [];
for (let i = 0; i < data.length; i++) {
let value = data[i];
if (value !== current) {
count = 0;
current = value;
}
if (++count === 5) {
result.push(value);
}
}
console.log(result);
答案 1 :(得分:0)
首先创建一个包含值及其出现次数的map
,然后根据出现次数从map
中提取值。
var data = ['1', '1', '1', '1', '1', '1', '1', '5', '5', '5', '5', '6', '7', '7', '7', '7', '7', '7']
var map = data.reduce(function(acc, item) {
if(acc[item]) acc[item] += 1;
else acc[item] = 1;
return acc;
}, {});
var result = Object.keys(map).filter(function(key) {
return map[key] >= 5;
})
console.log(result);
答案 2 :(得分:0)
试试这个,
var data=['1','1','1','1','1','1','1','5','5','5','5','6','7','7','7','7','7','7']
// Create an index mapping of format <value in data array>: <number of occurances>
var map = data.reduce((map, value)=>{
if (map[value])
map[value]++ // If occurred one or more times, we increment the occurrence count
else
map[value] = 1 // If first time occurrence, we set number of occurrences to 1
return map // return updated index map to reducer
}, {})
// Then we iterate through the index mapping
Object.keys(map).forEach((key)=>{
if(map[key] > 5) console.log(key) // Note: Here we should print the key, not the map[key]
})
答案 3 :(得分:0)
您可以执行以下操作:
var data=['1','1','1','1','1','1','1','5','5','5','5','6','7','7','7','7','7','7']
var counts = {};
data.forEach(function(item) { counts[item] = (counts[item] || 0)+1; });
var uniqueArray = Object.keys(counts).filter(function(key) {
return counts[key] >= 5;
});
console.log(uniqueArray);
&#13;