简体   繁体   中英

Comparing two arrays and pushing the result to new array

I have two arrays that are solely filled with strings. I am trying to compare the values in the strings and then push the strings to an empty array.

goupId = [
{'1','2','3','4'}]
homeGroups = 
[{'2','3', '4','1'}]
sameId =[];

this is my logic

compare: function(groupId, homeGroups) {
                this.groupId.forEach((e1)=>this.homeGroups.foreach((e2)=>{
                    if(e1 === e2){
                        this.sameId.push(e1)
                    }
                }
            ));
            }

I get the error TypeError: Cannot read property 'forEach' of undefined"

You need to drop the this. when referencing groupID and homeGroups as they are not member variables. You can learn more about this here .

Your code will end up looking like this.

compare: function(groupId, homeGroups) {
                groupId.forEach((e1)=>homeGroups.foreach((e2)=>{
                    if(e1 === e2){
                        this.sameId.push(e1)
                    }
                }
            ));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM