Array values that appear more than once [duplicate]

a 夏天 提交于 2019-12-13 02:38:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!