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!

  • [Array.prototype.push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Itay May 14 '16 at 17:34
  • Numerous javascript array methods you can use depending on expected results – charlietfl May 14 '16 at 17:35
  • Possible duplicate of [Appending to array](http://stackoverflow.com/questions/351409/appending-to-array) – rohithpr May 14 '16 at 17:44

4 Answers4

1

try this:

for(i = 0; i < products.length; i++) {
    if (products[i].category == "fruit") {
        fruits.push(products[i].name)
    }
}
Yuriy Yakym
  • 3,616
  • 17
  • 30
Jayaram
  • 6,276
  • 12
  • 42
  • 78
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);
Yuriy Yakym
  • 3,616
  • 17
  • 30
0

Use the filter API:

this.fruits = this.products.filter(function(product) {
                  return product.category == 'fruits';
              });
Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
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);
});
trincot
  • 317,000
  • 35
  • 244
  • 286