出现多次的数组值 [英] Array values that appear more than once
问题描述
我正在使用 lodash ,并且我有一个数组:
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).
似乎lodash可能有特定的方法,但是我看不到.像这样的const dups = _.duplicates(arr);
会很好.
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.
我有:
// 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..?
推荐答案
此任务不必使用lodash,您可以使用 Array.prototype.indexOf()
:
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"]
检查有效的演示.
或者用lodash简化一点:
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"]
这篇关于出现多次的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!