Go inside to compare if there are equal values

Asked

Viewed 92 times

2

I need to do one to check if inside my array this.variacaoForm.value.variacoes has a sku like the other, I tried something like:

for(let i=0;i<this.variacaoForm.value.variacoes.length;i++){
  for(let j=i+1;j<this.variacaoForm.value.variacoes.length;j++){
    if(this.variacaoForm.value.variacoes[i].sku == this.variacaoForm.value.variacoes[j].sku){
      console.log('possui sku iguais')
    }
  }
}

In my console.log is returning the message more than once when you have equal sku

I also tried to:

for(let i=0;i<this.variacaoForm.value.variacoes.length;i++){
  for(let j=0;j<this.variacaoForm.value.variacoes.length - 1;j++){
    if(this.variacaoForm.value.variacoes[j].sku == this.variacaoForm.value.variacoes[j+1].sku){
      console.log('sku iguasi')
    }
  }
}
  • 1

    utilize === (3 equal signs) in javascript. So it checks if the variable types are also equal. The == check whether the values, both string or number, are similar.

  • 1

    I don’t know what your array looks like, but it’s no longer simple to use a filter() that uses a function that checks whether the array contains elements more than once?

  • 1

    And what would be the expected result?

1 answer

2


It would be more interesting to use the method filter or map to traverse the two arrays, try to use this way.

this.variacaoForm.filter((value,index) => {
    return value.vairacoes.sku === this.variacaoForm.value.variacoes[index].sku });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.