简体   繁体   中英

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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM