1

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 duplicate values).

It seems like this is something lodash might have a specific method for, but I can't see one. Something like: const dups = _.duplicates(arr); would be nice.

I've got:

// object with array values and number of occurrences
const counts = _.countBy(arr, value => value);

// reduce object to only those with more than 1 occurrence
const dups = _.pickBy(counts, value => (value > 1));

// just the keys
const keys = _.keys(dups);

console.log(keys); // ['initials']

Is there a better way than this..?

Stephen Last
  • 5,491
  • 9
  • 44
  • 85
  • You can chain it to make it a lot less verbose, and you don't need the callback function in `_.countBy()`, **[see this example](https://jsfiddle.net/gq1o3Lk9/)**. Also, if you choose the **[_.filter solution](http://stackoverflow.com/questions/31681732/lodash-get-duplicate-values-from-an-array)**, then this question can be considered a duplicate. – ryeballar Apr 28 '16 at 10:44

2 Answers2

5

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);
  }
  return list;
}, []);

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"]
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
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.

baao
  • 71,625
  • 17
  • 143
  • 203