我正在尝试编写一个接受对象数组的函数,只选择对象中的特定键,并仅将该数组的唯一值返回到新的“已过滤”数组中。我正在尝试使用Array.filter并不断收到我的过滤数组未定义的错误。我哪里出错了?
const findUniques = function(arr) {
let rawArray = arr.map(res => res.id);
let filtered = rawArray.filter((id) => {
return filtered.indexOf(id) === -1;
});
console.log(filtered)
};
这是我过滤的数组的模拟。
1630489261, 1630489261, 1630489261, 1630489313, 1630489313, 1630489261, 1630489313, 1707502836, 1590711681, 1588295455, 1630489313, 1707502836, 1588295455, 1707502836, 1590711681, 1707502836, 1707502836, 1707502836, 1707502836, 1707502836, 1588295455, 1588295455
如果我将过滤器设置为全局变量,则会被填充,但不会被过滤。 I.E.过滤了rawArray中的所有内容。
答案 0 :(得分:1)
rawArray = [1, 2, 3, 2, 3, 1, 4];
filtered = rawArray.filter((e, i) => rawArray.indexOf(e) === i);
console.log(filtered);

let rawArray = [1, 2, 3, 2, 3, 1, 4],
filtered = rawArray.reduce(function (acc, item) {
if (!acc.includes(item)){
acc.push(item);
}
return acc;
}, []);
console.log(filtered);

答案 1 :(得分:0)
const values = [1630489261, 1630489261, 1630489261, 1630489313, 1630489313, 1630489261, 1630489313, 1707502836, 1590711681, 1588295455, 1630489313, 1707502836, 1588295455, 1707502836, 1590711681, 1707502836, 1707502836, 1707502836, 1707502836, 1707502836, 1588295455, 1588295455];
function unique(array) {
return array.reduce((a,b) => {
let isIn = a.find(element => {
return element === b;
});
if(!isIn){
a.push(b);
}
return a;
},[]);
}
let ret = unique(values);
console.log(ret);