Home > Software design >  Replace nested for loops Javascript
Replace nested for loops Javascript

Time:05-06

In my Angular application I am using 2 for loops over object and comparing the ids. Below is the code with nested for loops.

I have tried to achieve same output with filter and map but I do not get the same output.

How can I refactor 2 for loops and replace with less complexity code to get same output?

 this.initialData.forEach(spec => {
            this.amazonData1.forEach(s => {
                if (s.label === spec.label) {
                    spec.id = s.id;
                    return;
                }
            })
        })

This is what I have tried to

       this.initialData.map(function(spec){
            return this.amazonData1.filter(function(s){
                if (s.label === this.spec.label) {
                    spec.id = s.id;
                    return;
                }
            })

        })

CodePudding user response:

If one of your array object is monotonic, then you can apply binary search and reduce time complexity from O(n^2) to O(nlogn). Check this article on figuring out monotonous function: binary search

CodePudding user response:

Use find (the function becomes more "simple")

this.initialData.forEach(spec => {
    const data=this.amazonData1.find(x=>x.label==spec.label)
    spec.id=data?data.id:null
})

NOTE: In typescript don't use what-ever(function(s){...} else what-ever(s=>{...})

CodePudding user response:

You can use Map Like this

this.initialData.map(spec => {
    var data=this.amazonData1.find(x=>x.label==spec.label)
    spec.id=data?data.id:null
})
  • Related