Lodash获取唯一ID下具有最低值的项目

时间:2018-03-31 09:03:50

标签: javascript arrays lodash

我有一组对象代表一组游览,但同一游览有不同的价格,如下所示:

let tours = [{'id':1, price:200},
             {'id':1, price:300},
             {'id':3, price:150},
             {'id':2, price:110},
             {'id':3, price:120},
             {'id':2, price:100}]

所以,我想选择游览ID可用的最低价格并将其推入新阵列作为具有最低价格的独特游览。 结果将是:

result = [{'id':1, price:200},
          {'id':3, price:120},
          {'id':2, price:100},]

我在Lodash中尝试了类似_.minBy()的方法,但它从所有数组中返回一个。

2 个答案:

答案 0 :(得分:3)

Lodash解决方案

您可以_.groupBy() ID,而不是_.map()结果,并使用_.minBy()取每组的最低值:

const tours = [{"id":1,"price":200, prop: 'prop1' },{"id":1,"price":300, prop: 'prop1'},{"id":3,"price":150},{"id":2,"price":110},{"id":3,"price":120},{"id":2,"price":100}];

const result = _(tours)
  .groupBy('id')
  .map((group) => _.minBy(group, 'price'))
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

VanillaJS解决方案

Reducetours改为Map,其中ID为关键。在每次迭代中,以最低价格获取组。完成后,spread Map.values()返回数组:

const tours = [{"id":1,"price":200, prop: 'prop1' },{"id":1,"price":300, prop: 'prop1'},{"id":3,"price":150},{"id":2,"price":110},{"id":3,"price":120},{"id":2,"price":100}];
             
const lowest = [...tours.reduce((r, o) => {
  const { id, price } = o;
  const current = r.get(id);
  
  if(!current || price < current.price) r.set(id, { ...o });

  return r;
}, new Map()).values()];

console.log(lowest);

答案 1 :(得分:2)

或者您只需使用import Autolink from 'react-native-autolink'; class MyComponent extends Component { render() { return ( <Autolink text="This is the string to parse for urls (https://github.com/joshswan/react-native-autolink), phone numbers (415-555-5555), emails (josh@example.com), mentions/handles (@twitter), and hashtags (#exciting)" hashtag="instagram" mention="twitter" /> ); } } 继续更新累加器中的最小值

reduce

<强>演示

&#13;
&#13;
tours.reduce( (acc, c) => {
   acc[c.id] = acc[c.id] ? Math.min( c.price, acc[c.id] ) : c.price; //update min value in accumulator
   return acc;  // return  accumulator
} ,{}) //initialize accumulator to {}
&#13;
&#13;
&#13;