简体   繁体   English

无法仅过滤数组的唯一值

[英]Cannot filter only unique values of an array

I'm trying to write a function that accepts an array of objects, selects only a specific key in the objects and returns only the unique values of that array into a new "filtered" array. 我正在尝试编写一个接受对象数组的函数,仅选择对象中的特定键,然后仅将该数组的唯一值返回到新的“过滤”数组中。 I'm trying to use Array.filter and keep getting errors that my filtered array is undefined. 我试图使用Array.filter并不断收到错误消息,表明我的过滤数组未定义。 Where have I gone wrong? 我哪里出问题了?

const findUniques = function(arr) {


let rawArray = arr.map(res => res.id);

let filtered = rawArray.filter((id) => {
    return filtered.indexOf(id) === -1;
});
console.log(filtered)


};

Here is a mock of the array I'm filtered over. 这是我过滤过的数组的模拟。

1630489261, 1630489261, 1630489261, 1630489313, 1630489313, 1630489261, 1630489313, 1707502836, 1590711681, 1588295455, 1630489313, 1707502836, 1588295455, 1707502836, 1590711681, 1707502836, 1707502836, 1707502836, 1707502836, 1707502836, 1588295455, 1588295455

If I set filtered as a global variable it gets filled but it is not being filtered. 如果将filtered设置为全局变量,它将被填充,但不会被过滤。 IE filtered is being filled with everything in the rawArray. IE筛选器被rawArray中的所有内容填充。

Using Array#filter 使用Array#filter

 rawArray = [1, 2, 3, 2, 3, 1, 4]; filtered = rawArray.filter((e, i) => rawArray.indexOf(e) === i); console.log(filtered); 

Using Array#reduce 使用Array#reduce

 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); 

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);

https://jsfiddle.net/26bwknzf/4/ https://jsfiddle.net/26bwknzf/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM