簡體   English   中英

如何使用 Lodash 從數組中獲取唯一和最大元素

[英]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
  },
];

從上面的數組我想使用 lodash 在 id 和 max 值的基礎上獲取唯一元素

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

ES6 解決方案使用 Array#reduce 和Map來收集唯一值,然后使用Map#valuesspread 語法來獲取數組:

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

使用 lodash 您可以按label分組,然后映射組,並從每個組中取出具有最高value的項目:

 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>

這是一個使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM