TylerMayfield TylerMayfield - 2 months ago 10
Javascript Question

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!

Answer

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

Comments