1

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!

1
  • 1
    Please show all data as text, not as pictures of text. Note that getting data from JavaScript is often easier using console.log(JSON.stringify(obj, null, 2)) to get a string value you can then copy and paste. Please try to limit the amount of data to only enough to demonstrate the problem. Commented Feb 4, 2021 at 21:58

2 Answers 2

1

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);

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

Comments

1

your error is just on index!

tagdataexist.push(eewootags[j].id);// j and not i

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.