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.
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)
这也适用于未排序的数组.
小智 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)
另一种方法,但使用过滤器和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)
使用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
| 归档时间: |
|
| 查看次数: |
33951 次 |
| 最近记录: |