Wiseface
Wiseface

Reputation: 192

Why create a conditional checking if variable is -1 when iterating?

I'm sorry that this issue is hard to explain in a simple question but I have encountered it a couple times now and do not understand the functionality.

function checkArrays(batch){
  let newArray = [];
  for(var i = 0; i < batch.length; i++){
    let firstDigit = batch[i][0];
    if(newArray.indexOf(firstDigit) === -1){
      newArray.push(firstDigit);
    }
  }
  return new
}

corrected variable from new to newArray

This function takes in batch, a collection of arrays of single digits like [5,7,7,3,9,1,6,3]. The goal is to take the first digit of each array and add them to new, which is returned. My question is why is it necessary to check if new.indexOf(firstDigit) === -1 in order to do this? What is significant about -1 and why would one want to iterate this way? Thanks!

Upvotes: 0

Views: 42

Answers (1)

David
David

Reputation: 218808

This:

if(new.indexOf(firstDigit) === -1)

Basically means "if the element is not in the array", because indexOf:

... returns the first index at which a given element can be found in the array, or -1 if it is not present.

In most browsers you can also use includes which is more semantically descriptive:

if(!new.includes(firstDigit))

As an aside... new is probably not a great name for a variable, since it's an operator in the language itself. For this particular operation I'd go with something like result or newArray or something else a little more descriptive and not reserved.

Upvotes: 3

Related Questions