Something is missing Something is missing - 1 month ago 10
Javascript Question

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. 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. I.E. filtered is being filled with everything in the rawArray.

Answer Source

Using 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

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