Ste*_*ast 1 javascript arrays lodash
我正在使用lodash并且我有一个数组:
const arr = ['firstname', 'lastname', 'initials', 'initials'];
Run Code Online (Sandbox Code Playgroud)
我想要一个仅包含出现多次的值(重复值)的新数组。
看起来 lodash 可能有一种特定的方法,但我看不到。像这样的东西:const dups = _.duplicates(arr);那就太好了。
我有:
// 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']
Run Code Online (Sandbox Code Playgroud)
还有比这更好的方法吗..?
没有必要使用 lodash 来完成此任务,您可以使用纯 JavaScript 和 轻松实现Array.prototype.reduce()它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"]
Run Code Online (Sandbox Code Playgroud)
检查工作演示。
或者用 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"]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4560 次 |
| 最近记录: |