1

So guys, I don't how to give a topic to this one. I'm having trouble to copy data from array of Object to another newly created array.

For example, I want to copy and create a new array that contain all category of animals of every person in my database.

 people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

So, I created a new array named animalCategory to hold every category available.

 // declare new array to hold category of animals
 let animalCategory = []

This is the logic I came up with:-

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)

But unfortunately I got like a very big array of animalCategory as a result. And a lot of repetative animals category. (like shown below)

enter image description here

UPDATED: the output I want to seek is:-

animalCategory: [ 'cat', 'dog', 'iguana', 'fish']

How should I change my logic then? And is there any other way I can do this?

5
  • I'm having a hard time identifying what data you have to start with an what data you want as output. If people as defined in your first codeblock is your input, can you include a codeblock with your expected output? Commented May 29, 2020 at 4:16
  • @Chase Already updated the question. Please have a look Commented May 29, 2020 at 4:21
  • Is the issue the duplicate values? Or is there more? Commented May 29, 2020 at 4:22
  • @Chase Yes. How can I get rid of the duplicate values? That's the only thing I'm having trouble with Commented May 29, 2020 at 4:23
  • Got it. Added an answer that takes care of that and simplifies the array construction quite a bit. Commented May 29, 2020 at 4:27

5 Answers 5

1

people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

// declare new array to hold category of animals
 let animalCategory = []


// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            if(animalCategory.indexOf(animal.category) === -1) {
            
            animalCategory.push(animal.category);
            }
        }
    });
});

// see result
animalCategory.forEach(function(animal) {
    console.log(animal);
});

Hope this is helpfull.

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

Comments

1

Here's an example that gets the output you're looking for with duplicates removed.

people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ];
 
 const uniqAnimals = [...new Set(people.flatMap(p => p.animals).map(a => a.category))];
 
 console.log(uniqAnimals);

Comments

0

You could try using a Set. Set are made up of only unique values.

It wont matter if you push the same value it just won't add it to the set.

If you want to then convert the categories back to an array use the Array.from Method and pass in the set.

let animalCategory = new Set()
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
          animalCategory.add(animal.category)
    })
})
animalCategory = Array.from(animalCategory)

Comments

0

That's another solution.

people.forEach(people => {
   if (people.animals && people.animals.length) {
       people.animals.forEach(categories => {
           if (animalCategories.indexOf(categories.category) === -1) {
               animalCategories.push(categories.category);
           }
       });
   }
});

Comments

0

We can collect all category property values in array and from it we would remove duplicates values.

var people = [{
    name: "Person 1",
    animals: [{
        category: "cat"
      },
      {
        category: "dog"
      },
      {
        category: "fish"
      }
    ]
  },
  {
    name: "Person 2",
    animals: [{
        category: "dog"
      },
      {
        category: "iguana"
      }
    ]
  },
  {
    name: "Person 3",
    animals: [{
      category: "cat"
    }]
  }
];
var getArr = [];
var animalsArr = people.map(x => x.animals.map(y => {
  getArr.push(y.category);
}));

var filteredArr = getArr.filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredArr);

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.