lodash: Get duplicate values from an array

前端 未结 12 2211
执念已碎
执念已碎 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:16

    here is mine, es6-like, deps-free, answer. with filter instead of reducer

    // this checks if elements of one list contains elements of second list 
    // example code
    [0,1,2,3,8,9].filter(item => [3,4,5,6,7].indexOf(item) > -1)
    
    // function
    const contains = (listA, listB) => listA.filter(item => listB.indexOf(item) > -1) 
    contains([0,1,2,3], [1,2,3,4]) // => [1, 2, 3]
    
    // only for bool
    const hasDuplicates = (listA, listB) => !!contains(listA, listB).length
    

    edit: hmm my bad is: I've read q as general question but this is strictly for lodash, however my point is - you don't need lodash in here :)

    0 讨论(0)
  • 2020-12-09 08:25

    Another way is to group by unique items, and return the group keys that have more than 1 item

    _([1, 1, 2, 2, 3]).groupBy().pickBy(x => x.length > 1).keys().value()
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-09 08:30

    You can use this:

    _.filter(arr, (val, i, iteratee) => _.includes(iteratee, val, i + 1));
    

    Note that if a number appears more than two times in your array you can always use _.uniq.

    0 讨论(0)
  • 2020-12-09 08:35

    No need to use lodash, you can use following code:

    function getDuplicates(array, key) {
      return array.filter(e1=>{
        if(array.filter(e2=>{
          return e1[key] === e2[key];
        }).length > 1) {
          return e1;
        }
      })
    }
    
    0 讨论(0)
  • 2020-12-09 08:37
    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})));
    

    This works for unsorted arrays as well.

    0 讨论(0)
提交回复
热议问题