Home > Back-end >  Values being duplicated when pushing to an empty array
Values being duplicated when pushing to an empty array

Time:07-22

I am getting the industries from an API that I'm calling. I am getting the id and for each industry I want to only show the industries that are active by also calling my caseStudies from another API call. I am pushing the industry id that is being looked for in the API from the for loop and pushing it into activeIndustries array and then returning activeIndustries result. The issue is I am having duplicates. Duplicated industries. I think the issue is that industry is coming in as an object and activeIndustries is coming in as an array of objects so I think since they are not the 'same' they are reiterating. This is my console.log for study.industries, you can see the repeated IDs: Console log How can I stop this from duplicating and just show once? Thanks in advance!

 function getActiveIndustries() {
    const activeIndustries = [];
    industries.forEach((industry) => {
      //ex: industry.id = 374 -> a number
      console.log(`for each get active industries `   industry.id);
      for (let i = 0; i < caseStudies.length; i  ) {
        //ex: study is one object
        //study.industries = array of ids [374, 373]
        let study = caseStudies[i];
        console.log(`study `   study.industries);
        if (study.industries.includes(industry.id)) {
          activeIndustries.push(industry);

          //industry is an object {} & activeIndustries is an array of objects[{}]
        }
      }
    });

CodePudding user response:

I think the problem here is that you're constantly pushing the same industry onto activeIndustries.

e.g.

industries.forEach((industry) // let's presume industry = 1... Pretend industries = h... Pretend study starts at 0...

Within your for loop it'll generate on the first iteration... 0.h.includes(1) ? Presume that this passes, let's push industry "1" onto the array.

Second iteration... 1.h.includes(1)? Presume that it passes again, push same value "1" as before onto the array.

Now you already have a duplicated value on your array.

You're not changing the industry value until after your for loop is done... Within the foreach...

So that might be the case. Let me know if my answer helps you.

CodePudding user response:

This is assuming the caseStudies is an array of all the active industries you want to include have an id property?

From what I read you issue is that you are just seeing if the industry exists inside the caseStudies array. You weren't adding any conditional to determine if you should or shouldn't add the item if it exists in your activeIndustries array.

Array.prototype.includes() Array.includes() Just returns true or false, so your original conditional (study.industries.includes(industry.id) was always going to return true if it existed in that array. So if the array has duplicated values, those are also going to get pushed. But adding the conditional I added. Checks if it returns false meaning it doesn't exist inside the array yet in which it will add it.

function getActiveIndustries()
{
    const activeIndustries = [];
    industries.forEach((industry) => 
    {
        //ex: industry.id = 374 -> a number
        console.log(`for each get active industries `   industry.id);
        caseStudies.forEach((study) => //You for loop can also be a forEach to save writing.
        {
            console.log(`study ${study.industries}`);

            if(study.industries.includes(industry.id)) //Returns true if its in the case study- Which means its active? 
            {
                //So you need to also check to make sure the industry is not included in the activeIndustries
                //before adding it.
                if(!activeIndustries.includes(industry))
                    activeIndustries.push(industry);
            }

            //industry is an object {} & activeIndustries is an array of objects[{}]
        });
    });
}

CodePudding user response:

You can use a Set to extract unique ids from study.industries, which is an array of objects as well. Doing this will give you an array of ids (after using map over studies.industries, and then using the Set constructor over that array) which are unique.

function getActiveIndustries() {
    const activeIndustries = [];
    industries.forEach((industry) => {
      //ex: industry.id = 374 -> a number
      console.log(`for each get active industries `   industry.id);
      for (let i = 0; i < caseStudies.length; i  ) {
        //ex: study is one object
        //study.industries = array of ids [374, 373]
        let study = caseStudies[i];
        console.log(`study `   study.industries);

        // Modified Code
        // map iterates through all elements in study.industries
        const caseStudyIds = study.industries.map((element) => {
            return element.id;
        });

        // ... spread operator converts set back into an array
        const caseStudyIdsUnique = [...new Set(caseStudyIds)];
        if (caseStudyIdsUnique.includes(industry.id)) {
          activeIndustries.push(industry);
          //industry is an object {} & activeIndustries is an array of objects[{}]
        }
      }
    });
};
  • Related