Håkan Arnoldson
Håkan Arnoldson

Reputation: 19

JavaScript iteration vs filter map

I am wondering about the difference between this:

function doesCodeExist(arrvalidcodes, code) {

  var hit = arrvalidcodes.filter(function(item){
    return (code === item)
  }).map(function(item){
    return true;
  });
  if (hit[0] === true) {
    return true;
  } else {
    return false;
  }
}

and this:

function doesCodeExist(arrvalidcodes, code) {

  for (var i = 0; i < arrvalidcodes.lenght; i++) {
    if (arrvalidcodes[i] === code) {
      return true;
    }
  }
  return false;
}

Both codes should do the same thing, simply return true if the code is in the provided array or otherwise return false.

Which is considered the most readable and which is the more efficient way of doing it?

Upvotes: 1

Views: 93

Answers (2)

Oriol
Oriol

Reputation: 288120

Of course your first code is worse because it allocates various useless arrays and is not readable.

If you want semantic ES5 array methods, use some:

function doesCodeExist(arrvalidcodes, code) {
  return arrvalidcodes.some(function(item){
    return code === item;
  });
}

Of course, for just strict comparison you should use indexOf, or is you want a SameValueZero comparisson use includes.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386604

You could use Array#indexOf

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

function doesCodeExist(arrvalidcodes, code) {
    return arrvalidcodes.indexOf(code) !== -1;
}

or with ES6 use Array#includes

Upvotes: 1

Related Questions