lodash:从数组中获取重复值

zia*_*war 29 javascript arrays lodash

说我有这样的数组: [1, 1, 2, 2, 3]

我想得到这种情况下的重复项: [1, 2]

是否lodash支持呢?我想尽可能以最短的方式做到这一点.

saa*_*del 35

你可以用这个:

_.filter(arr, (val, i, iteratee) => _.includes(iteratee, val, i + 1));
Run Code Online (Sandbox Code Playgroud)

请注意,如果数组在数组中出现的次数超过两次,则可以随时使用_.uniq.

  • 单行,带有一些ES2015糖:`const duplicates = _.filter(array,(value,index,iteratee)=> _.includes(iteratee,value,index + 1)) (4认同)
  • 如果您使用_.find而不是_.includes` _.filter(array,(value,index,iteratee)=> {返回_.find(iteratee,value,index +1)})` (2认同)
  • 您能为那些不太熟悉iteratee的人添加说明吗? (2认同)

Gaa*_*far 23

另一种方法是按唯一项分组,并返回包含多个项的组键

_([1, 1, 2, 2, 3]).groupBy().pickBy(x => x.length > 1).keys().value()
Run Code Online (Sandbox Code Playgroud)


Mik*_*nov 13

var array = [1, 1, 2, 2, 3];
var groupped = _.groupBy(array, function (n) {return n});
var result = _.uniq(_.flatten(_.filter(groupped, function (n) {return n.length > 1})));
Run Code Online (Sandbox Code Playgroud)

这也适用于未排序的数组.

  • 对于较大的阵列而言,这似乎比接受的答案要快得多.干得好. (2认同)

小智 6

纯JS解决方案:

export function hasDuplicates(array) {
  return new Set(array).size !== array.length
}
Run Code Online (Sandbox Code Playgroud)

对于对象数组:

/**
 * Detects whether an array has duplicated objects.
 * 
 * @param array
 * @param key
 */
export const hasDuplicatedObjects = <T>(array: T[], key: keyof T): boolean => {
  const _array = array.map((element: T) => element[key]);

  return new Set(_array).size !== _array.length;
};
Run Code Online (Sandbox Code Playgroud)


Raf*_*ffa 5

另一种方法,但使用过滤器和ecmaScript 2015(ES6)

var array = [1, 1, 2, 2, 3];

_.filter(array, v => 
  _.filter(array, v1 => v1 === v).length > 1);

//? [1, 1, 2, 2]
Run Code Online (Sandbox Code Playgroud)


Bri*_*ark 5

使用countBy()后跟怎么样reduce()

const items = [1,1,2,3,3,3,4,5,6,7,7];

const dup = _(items)
    .countBy()
    .reduce((acc, val, key) => val > 1 ? acc.concat(key) : acc, [])
    .map(_.toNumber)

console.log(dup);
// [1, 3, 7]
Run Code Online (Sandbox Code Playgroud)

http://jsbin.com/panama/edit?js,console