Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

JavaScript get common element in two arrays

I have this array which is eewootags:

enter image description here

and I have another array evProductTag which is below:

enter image description here

I am trying to get the id which is common to both.

This is what I tried:

var tagdataexist = [];
for (var i = 0; i < evProductTag.length; i++) {
  for (var j = 0; j < eewootags.length; j++) {
    if (eewootags[j].name == evProductTag[i].name){
      tagdataexist.push(eewootags[i].id);
    }
  }
}
console.log(tagdataexist);

But this gives be 193 instead of 187.
Tag2 is the common element by name.

Please help!

question from:https://stackoverflow.com/questions/66054419/javascript-get-common-element-in-two-arrays

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is with the indexes of your array: you access eewootags with both i and j. You need to use always the same index!

let eewootags = [
  {id: 193, name: 'Tag 8'},
  {id: 186, name: 'Tag1'},
  {id: 187, name: 'Tag2'},
  {id: 188, name: 'Tag3'},
  {id: 189, name: 'Tag4'},
  {id: 190, name: 'Tag5'},
  {id: 191, name: 'Tag6'},
  {id: 192, name: 'Tag7'},
  {id: 194, name: 'Tag9'}
];
let evProductTag = [
  {name: 'Tag2'},
  {name: 'Tag 3'},
  {name: 'Tag 69'}
];
let tagdataexist = [];
for (let i = 0; i < eewootags.length; i++) {
  for (let j = 0; j < evProductTag.length; j++) {
    if (eewootags[i].name == evProductTag[j].name) {
      tagdataexist.push(eewootags[i].id);
    }
  }
}
console.log(tagdataexist);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...