lodash: Get duplicate values from an array

前端 未结 12 2246
执念已碎
执念已碎 2020-12-09 08:14

Say I have an array like this: [1, 1, 2, 2, 3]

I want to get the duplicates which are in this case: [1, 2]

Does lodash support thi

12条回答
  •  孤街浪徒
    2020-12-09 08:28

    Well you can use this piece of code which is much faster as it has a complexity of O(n) and this doesn't use Lodash.

    [1, 1, 2, 2, 3]
    .reduce((agg,col) => {
      agg.filter[col] = agg.filter[col]? agg.dup.push(col): 2;
      return agg
     },
     {filter:{},dup:[]})
    .dup;
    
    //result:[1,2]
    

提交回复
热议问题