Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Remove Unique Elements from Array

I am wondering how one would go about removing unique elements from an array. For example:

var arr = [1, 2, 2, 4, 4] would return [2, 2, 4, 4]. Where [1, 2, 3] would return [] because all elements are unique.

I believe I need to check each element with every other element in the array, but I'm not sure how to go about this.

Thanks!

like image 862
TylerMayfield Avatar asked Sep 20 '16 16:09

TylerMayfield


1 Answers

With ES6, you could use a Array#map and count the values with Array#forEach.

Later use Array#filter and check the count.

If greater than 1 return true (include the item in the result set), otherwise return false (do not include item in the result set).

function getNotUnique(array) {
    var map = new Map();
    array.forEach(a => map.set(a, (map.get(a) || 0) + 1));
    return array.filter(a => map.get(a) > 1);
}

console.log(getNotUnique([1, 2, 2, 4, 4]));
console.log(getNotUnique([1, 2, 3] ));
like image 61
Nina Scholz Avatar answered Oct 05 '22 08:10

Nina Scholz