如何使用Lodash从数组中获取unique和max元素

时间:2017-10-23 14:20:13

标签: javascript 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我希望使用lodash

在id和max值的基础上获得Unique元素

2 个答案:

答案 0 :(得分:2)

使用Array#reduce的ES5解决方案:



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);




使用Array#reduce和Map收集唯一值的ES6解决方案,然后使用Map#valuesspread syntax获取数组:



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);




答案 1 :(得分:1)

这是使用lodash#orderBylodash#uniqBy的lodash解决方案。

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>
&#13;
&#13;
&#13;