Husnain Khan
Husnain Khan

Reputation: 23

How to get the unique and max element from array using Lodash

var data = [
  {
    label: 'tagA',
    value: 1
  },
  {
    label: 'tagB',
    value: 2
  },
  {
    label: 'tagC',
    value: 3
  },
  {
    label: 'tagB',
    value: 4
  },
  {
    label: 'tagB',
    value: 5
  },
];

From Above Array I want to get Unique element on the base of id and max value using lodash

Upvotes: 2

Views: 2645

Answers (2)

Ori Drori
Ori Drori

Reputation: 192287

An ES5 solution using Array#reduce:

var data = [{"label":"tagA","value":1},{"label":"tagB","value":2},{"label":"tagC","value":3},{"label":"tagB","value":4},{"label":"tagB","value":5}];

var helper = {};
var result = data.reduce(function(r, o) {
  if(!helper[o.label]) {
    r.push((helper[o.label] = Object.assign(o)));
  } else {
    o.value > helper[o.label].value && (helper[o.label].value = o.value);
  }
  
  return r;
}, []);

console.log(result);

An ES6 solution using Array#reduce and Map to collect the unique values, and then using Map#values, and spread syntax to get an array:

const data = [{"label":"tagA","value":1},{"label":"tagB","value":2},{"label":"tagC","value":3},{"label":"tagB","value":4},{"label":"tagB","value":5}];

const result = [...data.reduce((map, o) => 
  map.has(o.label) && map.get(o.label).value > o.value ? 
    map : map.set(o.label, o), new Map).values()];
console.log(result);

With lodash you can group by the label, and then map the groups, and take the item with the highest value from each group:

const data = [{"label":"tagA","value":1},{"label":"tagB","value":2},{"label":"tagC","value":3},{"label":"tagB","value":4},{"label":"tagB","value":5}];

const result = _.map( // map the groups
  _.groupBy(data, 'label'), // group by the label
  g => _.maxBy(g, 'value') // take the one with the highest value of each group
)
  
console.log(result);
.as-console-wrapper{min-height:100%;top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 4

ryeballar
ryeballar

Reputation: 30108

Here's a lodash solution that uses lodash#orderBy and lodash#uniqBy.

var result = _(data)
  .orderBy(['label', 'value'], ['asc', 'desc'])
  .uniqBy('label')
  .value();

var data = [
  {
    label: 'tagA',
    value: 1
  },
  {
    label: 'tagB',
    value: 2
  },
  {
    label: 'tagC',
    value: 3
  },
  {
    label: 'tagB',
    value: 4
  },
  {
    label: 'tagB',
    value: 5
  },
];

var result = _(data)
  .orderBy(['label', 'value'], ['asc', 'desc'])
  .uniqBy('label')
  .value();
  
console.log(result);
.as-console-wrapper{min-height:100%;top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

Related Questions