Skip to content Skip to sidebar Skip to footer

Array Values That Appear More Than Once

I'm using lodash and I have an array: const arr = ['firstname', 'lastname', 'initials', 'initials']; I want a new array containing only the values that appear more than once (the

Solution 1:

It's not necessary to use lodash for this task, you can easily achieve it using plain JavaScript with Array.prototype.reduce() and Array.prototype.indexOf():

var arr = ['firstname', 'lastname', 'initials', 'initials', 'a', 'c', 'a', 'a', 'c'];

var dupl = arr.reduce(function(list, item, index, array) { 
  if (array.indexOf(item, index + 1) !== -1 && list.indexOf(item) === -1) {
    list.push(item);
  }
  returnlist;
}, []);

console.log(dupl); // prints ["initials", "a", "c"]

Check the working demo.


Or a bit simpler with lodash:

var arr = ['firstname', 'lastname', 'initials', 'initials', 'a', 'c', 'a', 'a', 'c'];

var dupl = _.uniq(_.reject(arr, function(item, index, array) { 
  return_.indexOf(array, item, index + 1) === -1; 
}));

console.log(dupl); // prints ["initials", "a", "c"]

Solution 2:

You can use this

let dups = _.filter(array, (val, i, it) => _.includes(it, val, i + 1));

If you only want unique duplicates in your dups array, you may use _.uniq() on it.

Post a Comment for "Array Values That Appear More Than Once"