2

So I have an array

var items = [];
items.push({
    name: "milk",
    id: "832480324"
});
  items.push({
    name: "milk",
    id: "6234312"
});
 items.push({
    name: "potato",
    id: "983213"
});
  items.push({
    name: "milk",
    id: "131235213"
});

Then I have a function order(name, amount). If I call it like order(milk, 2) then it should show me 2 ID's of milk in the items array. How could I achieve that? (Yeah, I had to make a new question)

4
  • Why just 2 ID's (where name is 'milk') when you have 3 in your example? Commented Jun 16, 2016 at 15:35
  • 2
    how do you know which id(s) you want, the first 2, last 2? Commented Jun 16, 2016 at 15:36
  • I mean, not just 2 the number can be chosen by person. Example if he wants 3, then he chooses three and shows those 3 different id's. If 1 then one ID etc. Commented Jun 16, 2016 at 15:38
  • If he choose 1, should it be the first, the middle or the last? What is the criteria for selection? Also shouldn't it be order("milk", 2) - with strings? Commented Jun 16, 2016 at 15:49

2 Answers 2

3

Use a simple for loop

var items = [];
items.push({
  name: "milk",
  id: "832480324"
});
items.push({
  name: "milk",
  id: "6234312"
});
items.push({
  name: "potato",
  id: "983213"
});
items.push({
  name: "milk",
  id: "131235213"
});

function order(name, count) {
  var res = [];
  // iterate over elements upto `count` reaches
  // or upto the last array elements
  for (var i = 0; i < items.length && count > 0; i++) {
    // if name value matched push it to the result array
    // and decrement count since one element is found
    if (items[i].name === name) {
      // push the id value of object to the array
      res.push(items[i].id);
      count--;
    }
  }
  // return the id's array
  return res;
}
console.log(order('milk', 2));

Sign up to request clarification or add additional context in comments.

Comments

0

A functional ES6 method that I like for its readability is to use filter().map().slice():

var items = [{name:"milk",id:"832480324"},{name:"milk",id:"6234312"},{name:"potato",id:"983213"},{name:"milk",id:"131235213"}];

function order(name, amount) {
  return items.filter(i => i.name === name)
              .map(i => i.id)
              .slice(0, amount);
}

console.log(order('milk', 2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.