filterfirst和filterlast

filterfirst和filterlast

假设我们有一系列产品,如下所示,产品按名称排序,然后按价格排序。
如何使用lodash获得每个类别中最便宜的产品或最昂贵的产品?
我们需要类似filterfirstfilterlast的功能。

[
    {
      "productId": "123456",
      "name": "Daiper",
      "category": "Home",
      "store": "store1",
      "pricing": 10
    },
    {
      "productId": "123457",
      "name": "Daiper",
      "category": "Home",
      "store": "store2",
      "pricing": 20
    },
    {
      "productId": "123458",
      "name": "Daiper",
      "category": "Home",
      "store": "store3",
      "pricing": 30
    },
    {
      "productId": "123466",
      "name": "Paint",
      "category": "Home",
      "store": "store2",
      "pricing": 25
    },
    {
      "productId": "123467",
      "name": "Paint",
      "category": "Home",
      "store": "store1",
      "pricing": 36
    },
    {
      "productId": "123468",
      "name": "Paint",
      "category": "Home",
      "store": "store3",
      "pricing": 80
    }
]

最佳答案

您可以通过_.groupBy()属性name项,然后_.map()组数组到每个组的第一个或最后一个项目:



function filterGroups(groupIdProp, predicate) {
  return function(arr) {
    return _(arr)
      .groupBy(groupIdProp)
      .map(predicate)
      .values();
  }
}

var filterFirst = filterGroups('name', function(group) {
  return group[0];
});

var filterLast = filterGroups('name', function(group) {
  return group[group.length - 1];
})

var arr = [{
  "productId": "123456",
  "name": "Daiper",
  "category": "Home",
  "store": "store1",
  "pricing": 10
}, {
  "productId": "123457",
  "name": "Daiper",
  "category": "Home",
  "store": "store2",
  "pricing": 20
}, {
  "productId": "123458",
  "name": "Daiper",
  "category": "Home",
  "store": "store3",
  "pricing": 30
}, {
  "productId": "123466",
  "name": "Paint",
  "category": "Home",
  "store": "store2",
  "pricing": 25
}, {
  "productId": "123467",
  "name": "Paint",
  "category": "Home",
  "store": "store1",
  "pricing": 36
}, {
  "productId": "123468",
  "name": "Paint",
  "category": "Home",
  "store": "store3",
  "pricing": 80
}];

console.log('first', filterFirst(arr));

console.log('last', filterLast(arr));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

关于javascript - 带有lodash的filterfirst和filterlast函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39215931/

10-11 13:00