问题
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..?
回答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);
}
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"]
回答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.
来源:https://stackoverflow.com/questions/36911712/array-values-that-appear-more-than-once