Mysterious Organism step 5

Hi, I’m doing step 5 of this project. The codes below are working however

compareDNA(obj) {
      let identical = 0;
      for (let i = 0; i < this.dna.length; i++) {
        if (this.dna[i] === obj.dna[i]) {
          identical++
        }
      }
      return identical;
}

However I want to utilize ES6 iterations such as forEach() or much shorter syntax. I tried doing that but it shows different output than what the above codes do. What am I doing wrong?

compareDNA(obj) {
      let identical = 0;
      this.dna.forEach(item => item === obj.dna.forEach(element => element) ? identical++ : null;
      return identical;
}

Hi @cedd.hije
why are you running forEach twice?

I’m looping through the array of both this.dna and obj.dna arrays then comparing each element of both arrays

I tried doing this but it shows both arrays have identical elements.

compareDNA(obj) {
      let identical = 0;
      this.dna.forEach(val => {
        if (obj.dna.includes(val)) {
          identical++
        }
      })
      return identical;
    }

You can also use the index as a parameter in the forEach method:

arr.forEach( (element, index) =>{ 
// function
});

Have you also considered the include method? Or do you just want to find the elements with the same value and the same index?

Hi, I appreciate your quick response. I want to find the elements with just the same value and the solution that you offer looks good so I’ll try this and will reply again. Thank you for your help :slight_smile:

I’ve completed step. You’re right, I should have added index parameter. Thanks again for your help :slight_smile:

compareDNA(obj) {
      let identical = 0
      this.dna.forEach( (element, index) => element === obj.dna[index] ? identical++ : identical += 0)
      let percentage = Math.floor(identical / this.dna.length * 100)
      return `specimen #1 and specimen #2 have ${percentage}% DNA in common.`
    }
1 Like