简体   繁体   English

根据嵌套对象值收集对象数组

[英]Collect array of objects based on nested object value

I have an array of products (objects). 我有一系列的产品(对象)。 I want to get the biggest bang for your buck by obtaining the most Base with as little money as possible (in this case, $50). 我想通过以尽可能少的钱(在本例中为$ 50)获得最大的Base来获得最大的收益。 For the data set below, the correct outcome will contain an array of foo bar and baz products. 对于以下数据集,正确的结果将包含foo barbaz乘积数组。

 "result": [
  {
   "name": "foo",
   "price": 20,
   "Base": 52,
  },
  {
   "name": "bar",
   "price": 12,
   "Base": 51,
  },
  {
   "name": "baz",
   "price": 15,
   "Base": 50,
  },
  {
   "name": "qux",
   "price": 10,
   "Base": 47,
  },
 ]

Originally I thought I would use a reducer with an initial accumulator of [] , but my products I have can range anywhere between 600 - 2000 products and I don't think it would be performant.ie 最初,我以为我会使用带有[]的初始累加器的减速器,但是我拥有的产品范围可能在600-2000种产品之间,而我认为它不会表现出色。

function selectProducts(results){
  let finalList = []
  let priceList = []
  results.forEach(function(product){
    let price = product.price
    let sum = priceList.reduce(function(accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0);
    if (product.price + sum <= 50){
      finalList.push(product);
      priceList.push(price);
    }
  })
  return finalList
}

I don't like this code because I'm keeping track of two arrays when I don't think I need to. 我不喜欢此代码,因为当我认为不需要时,我会跟踪两个数组。 As far as I can see, the output of the above is correct, however I'm curious to see if my implementation can be improved. 据我所知,上面的输出是正确的,但是我很好奇我的实现是否可以改进。 thanks!!! 谢谢!!!

It seems like what you really want to do is keep track of the priceList. 看来您真正想要做的是跟踪priceList。 Then why not convert the forEach loop to reduce, and then the accumulator can be the priceList? 那为什么不转换forEach循环来减少它,然后累加器可以成为priceList? You can choose internally if you want to add to the accumulating value, and then you can get rid of the internal reduce. 如果要增加累加值,则可以在内部进行选择,然后可以摆脱内部的减少。

function selectProducts(results){
  let finalList = []
  results.reduce(function(acc, product){
    if (product.price + acc <= 50){
      finalList.push(product);
      return acc + product.price;
    } else {
      return acc;
    }
  }, 0)
  return finalList
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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