简体   繁体   中英

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). For the data set below, the correct outcome will contain an array of foo bar and baz products.

 "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

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. Then why not convert the forEach loop to reduce, and then the accumulator can be the 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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