Home > OS >  Filtering an array for only unique values [duplicate]
Filtering an array for only unique values [duplicate]

Time:10-06

for example if arr = [1,1,2,3,5,5] this will return [1,2,3,5].

function returnUnique(arr) {
      
      let unique = [...new Set(arr)];
      return unique;
    };

my goal is to return only 2,3

CodePudding user response:

function returnUnique(arr) {
  return arr.filter(e => arr.indexOf(e) === arr.lastIndexOf(e));
}

console.log( returnUnique([1,1,2,3,5,5]) );

CodePudding user response:

You can easily achieve the result using Map

const arr = [1, 1, 2, 3, 5, 5];

const map = new Map();
arr.forEach((n) => map.set(n, (map.get(n) ?? 0)   1));

const result = [];
for (let [k, v] of map) {
  if (v === 1) result.push(k);
}

console.log(result);

CodePudding user response:

Use reduce function, for example:

const array = [1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6];

const uniqueValues = (array) => array.reduce((arr, item) => {
if (!arr.some((filteredItem) =>
        JSON.stringify(filteredItem) === JSON.stringify(item)
    ))
    arr.push(item);
return arr;
}, []);
console.log(uniqueValues(array))

  • Related