0

Something I'm trying to do in an angularjs app that I'm making. I have a large array of the cast of a movie including directors, producers, film crew etc. and I want to make a new array of just the director(s).

I don't know how to fill a new array with specific objects form another array. Here's a quick simple example of what I mean:

this.products = [
  {name: "apple", category: "fruit"}, 
  {name: "iPhone", category: "tech"}, 
  {name: "banana", category: "fruit"}
];

this.fruits = [];

for(i = 0; i < products.length; i++) {
  if (products.category[i] == "fruit") {
    /*code to add object to fruits array*/
 }
}

Please help! Thank you!

3
  • Array.prototype.push Commented May 14, 2016 at 17:34
  • Numerous javascript array methods you can use depending on expected results Commented May 14, 2016 at 17:35
  • Possible duplicate of Appending to array Commented May 14, 2016 at 17:44

4 Answers 4

1

Try with this code this may do helpful for you

this.products = [
    {name: "apple", category: "fruit"}, 
    {name: "iPhone", category: "tech"}, 
    {name: "banana", category: "fruit"}
];

this.fruits = [];

for(i = 0; i < products.length; i++) {
    if (products[i].category === "fruit") {
        /*code to add object to fruits array*/

        fruits.push(products[i].name);
    }
}

console.log(fruits);
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

for(i = 0; i < products.length; i++) {
    if (products[i].category == "fruit") {
        fruits.push(products[i].name)
    }
}

Comments

0

Use the filter API:

this.fruits = this.products.filter(function(product) {
                  return product.category == 'fruits';
              });

Comments

0

You can do this as follows:

this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name);

The .filter() method takes only the objects with the right category. Then .map() goes through this result, and replaces the objects by the name property value only, so that the final result is ["apple", "banana"].

If you want the objects as a whole, then of course you leave out the .map() part.

Demo:

new (function () {
    this.products = [
      {name: "apple", category: "fruit"}, 
      {name: "iPhone", category: "tech"}, 
      {name: "banana", category: "fruit"}
    ];

    this.fruits = this.products.filter(p => p.category == "fruit").map(p => p.name);

    document.write(this.fruits);
});

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.