yerme
yerme

Reputation: 855

How to add items from multiple arrays into another array?

I have an array of objects I'm looping over with Vue. Each object has a key value pair with the value being another array. How can I loop over each object and then loop over each array in that object to add all unique items to one array?

 const objects: [
   {
      hungry: true,
      name: "pete",
      fruits: ["banana", "orange"]
   },
   {
      hungry: false,
      name: "sam",
      fruits: ["grapes", "kiwi"]
   },
   {
      hungry: true,
      name: "george",
      fruits: ["pear", "mango"]
   }
 ]

This gets me close but it just adds each inner array to the outer array, not the unique items in that array ...

      uniqueFruits: function() {
            const fruitList = [];
            this.objects.forEach((object)=>{
                if (!fruitList.includes(object.fruits)) {
                    fruitList.push(objects.fruits);
                }
            });
            return fruitList;
        }

I know I need to loop inside again somehow to get the items in the inner array. Any help?

Upvotes: 1

Views: 567

Answers (2)

L-Tan
L-Tan

Reputation: 121

Using nested loop is one way, with es6 you can instead of doing fruitList.push(objects.fruits);, do: fruitList = [...fruitList, ...objects.fruits];

One way to remove duplicates is that after having the entire fruitList, convert it to a set by const fruitSet = new Set(fruitList);. This will leave you only unique fruit names. If you need an array type, just const fruitArray = Array.from(fruitSet);.

Upvotes: 1

Tân
Tân

Reputation: 1

I think you're looking for something like this:

const objects = [
   {
      hungry: true,
      name: "pete",
      fruits: ["banana", "orange"]
   },
   {
      hungry: false,
      name: "sam",
      fruits: ["grapes", "kiwi"]
   },
   {
      hungry: true,
      name: "george",
      fruits: ["pear", "mango"]
   }
 ];
 
const fruitList = [];

objects.forEach(item => item.fruits.forEach(fruit => fruitList.push(fruit)));

console.log(fruitList);


Update:

If you want to check duplicate fruit name before pushing, you can edit the code to:

    const objects = [
       {
          hungry: true,
          name: "pete",
          fruits: ["banana", "orange"]
       },
       {
          hungry: false,
          name: "sam",
          fruits: ["grapes", "banana"]
       },
       {
          hungry: true,
          name: "george",
          fruits: ["orange", "mango"]
       }
     ];
     
    const fruitList = [];

    objects.forEach(item => item.fruits.forEach(fruit => {
        if (fruitList.indexOf(fruit) < 0) {
            fruitList.push(fruit);
        }
    }));

    console.log(fruitList);

Upvotes: 2

Related Questions