Search code examples
javascriptarrayslodashjavascript-objects

Get unique values from an array of objects


[
  {key1 : 'sometext'},
  {key2 : 'sometext'},
  {key1 : 'sometext'},
  {key3 : 'sometext'},
]

From the above code I need to get the results as follows, removing objects that contains same keys

[
  {key1 : 'sometext'},
  {key2 : 'sometext'},
  {key3 : 'sometext'},
]

Thanks in advance.


Solution

  • With lodash you can use _.uniqBy(), and return the single key of each object:

    const arr = [{"key1":"sometext"},{"key2":"sometext"},{"key1":"sometext"},{"key3":"sometext"}]
    
    const result = _.uniqBy(arr, o => _.keys(o)[0])
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    Using vanilla JS, if you don't care if the 2nd item (the duplicate would be used, you can combine all items to a single object (this will remove the 1st duplicate), get the entries, and map back to an array of objects:

    const arr = [{"key1":"sometext"},{"key2":"sometext"},{"key1":"sometext"},{"key3":"sometext"}]
    
    const result = Object.entries(Object.assign({}, ...arr))
      .map(([k, v]) => ({ [k]: v }))
    
    console.log(result)