Miha Šušteršič
Miha Šušteršič

Reputation: 10042

javascript nesting a for loop inside an array filter

I'm solving a coding exercise and ran into a interesting problem. I am trying to filter an array by arguments (I don't know in advance how many arguments there will be). So the first argument of my function is always an array, followed by a random number of integers I need to filter out.

I figured I'd solve this by nesting a for loop inside my filter function, but so far it only filters by the first argument and ignores the second one. Is this due to using return false/true? If so, what could I use instead?

function destroyer(arr) {
  var output = [];
  for (var y = 1; y < arguments.length; y++) {
    output.push(arguments[y]);
  }

  function destroy(value) {
    for (var x = 0; x < output.length; x++) {
      if (value === output[x]) {
        return false;
      } else {
        return true;
      }
    }
  }
  return arr.filter(destroy);
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Thanks for the help

Upvotes: 2

Views: 9337

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

Please move the return true to the end of the function, because the for loop should stop only, if a not wanted value is found.

function destroyer(arr) {
    var output = [];
    for (var y = 1; y < arguments.length; y++) {
        output.push(arguments[y]);
    }

    function destroy(value) {
        for (var x = 0; x < output.length; x++) {
            if (value === output[x]) {
                return false;
            }
        }
        return true;
    }
    return arr.filter(destroy);
}

document.write(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

Upvotes: 4

synthet1c
synthet1c

Reputation: 6282

that is way more complicated than it needs to be. this does the same thing in less lines of code, and I would argue that it's more explicit and easier to read

function destroyer(arr) {
  // get all the arguments after the initial array
  var output = Array.prototype.slice.call(arguments, 1);
  // filter the output
  return arr.filter(function destroy(value) {
    // only return the numbers that aren't in the output array
    return output.indexOf( value ) < 0;
  });
  // profit.
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Upvotes: 2

Related Questions