How can I get a unique array based on object property using underscore

前端 未结 8 1196
遇见更好的自我
遇见更好的自我 2020-12-29 18:30

I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?

Eg.



        
相关标签:
8条回答
  • 2020-12-29 18:52

    Use the uniq function

    var destArray = _.uniq(sourceArray, function(x){
        return x.name;
    });
    

    or single-line version

    var destArray = _.uniq(sourceArray, x => x.name);
    

    From the docs:

    Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

    In the above example, the function uses the objects name in order to determine uniqueness.

    0 讨论(0)
  • 2020-12-29 18:57

    I was looking for a solution which didn't require a library, and put this together, so I thought I'd add it here. It may not be ideal, or working in all situations, but it's doing what I require, so could potentially help someone else:

    const uniqueBy = (items, reducer, dupeCheck = [], currentResults = []) => {
      if (!items || items.length === 0) return currentResults;
      
      const thisValue = reducer(items[0]);
      
      const resultsToPass = dupeCheck.indexOf(thisValue) === -1 ?
        [...currentResults, items[0]] : currentResults;
        
      return uniqueBy(
        items.slice(1),
        reducer,
        [...dupeCheck, thisValue],
        resultsToPass,
      );    
    }
    
    const testData = [
      {text: 'hello', image: 'yes'},
      {text: 'he'},
      {text: 'hello'},
      {text: 'hell'},
      {text: 'hello'},
      {text: 'hellop'},
    ];
    
    const results = uniqueBy(
      testData,
      item => {
        return item.text
      },
    )
    
    console.dir(results)

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