0

I need to check equals values in my array. I try many ways but no one works.

I try:

var sorted_arr = this.variacaoForm.value.variacoes.sort();  the comparing function here. 

for (var i = 0; i < this.variacaoForm.value.variacoes.length - 1; i++) {
    if (sorted_arr[i + 1].sku == sorted_arr[i].sku) {
        console.log('Equals elements array')
    }
}

In this way, the first and the third element never fire a console.log()

Also try:

for(let i=0;i<this.variacaoForm.value.variacoes.length;i++){
  if(this.produto.sku_prin == this.variacaoForm.value.variacoes[i].sku){
    console.log('Equal values array');
  }
}

in this way i receive console.log same if i don't have equal value

Also:

  for (let i = 0; i < this.variacaoForm.value.variacoes.length-1; 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('x')
           }
      }
  }     
  • What key is your sort function using to sort off of? It looks like `this.variacaoForm.value.variacoes` is an array of objects with `sku` being a property? Check https://stackoverflow.com/a/1129270/3716049 out. – User 5842 Feb 05 '19 at 19:28

1 Answers1

1

Just use an arrow function with filter, index & lastIndex, it will print the value that are duplicated.

    const data = [2, 4, 1, 3, 9, 3, 1];
    console.log(data.filter(a => data.indexOf(a) !== data.lastIndexOf(a))); 

The output will be an array of duplicated value. If you wanna deep in filter, just search for map, filter, reduce operator.

Robert
  • 554
  • 5
  • 13