0

Can anyone please help me out with this code? Apparently, I just figured out that one can't run a for loop within a filter function. How can I check all the items in array "a" in the filter function?

function destroyer(arr) {
  // Remove all the values
  var a = [];
  for (var i = 1;i < arguments.length;i++){
    a.push(arguments[i]);
  }
  return arr.filter(function(x){ 
    for (var b = 0;b <a.length;b++) { if (x !== a[b]){return x;} }
  });
}
j08691
  • 204,283
  • 31
  • 260
  • 272
toonday
  • 501
  • 4
  • 13
  • 4
    *" one can't run a for loop within a filter function"* That's an incorrect assumption. `.filter` has to either return `true` or `false`, **not** the element that should be in the result array. Have a look at the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter. What exactly is the function supposed to do? What's the expected output for which input? – Felix Kling May 27 '16 at 17:34
  • Ok, the function is supposed to return members of arr that are not in array "a". – toonday May 27 '16 at 17:43
  • 1
    Then the logic in your filter is wrong. With minimal changes it should be `for(...) { if (x === a[b]) { return false; } }; return true;`. `if (x !== a[b]){return x;}` is wrong in two ways: It returns the element instead of `true` or `false`. And assuming you mean that `x` should be included, this would include `x` if *any one* element in `a` is different from `x`. E.g. if you had `f([1,2,3], 1,2,3)` it would return `[1,2,3]`, since `1` is different from `2`, `2` is different from `1` and `3` is different from `1`. – Felix Kling May 27 '16 at 17:45
  • `Array.prototype.diff = function(a) { return this.filter(function(i) {return a.indexOf(i) < 0;}); };`http://stackoverflow.com/a/4026828/1214902 – dap.tci May 27 '16 at 17:48

1 Answers1

0

Array filter methods take a callback function definition which is returns true or false. true will include the item in the resulting array. false will exclude it.

Here is an example of how to use .filter():

var arr = [1,2,3,4,'a','b','c','d'];

var filteredArr = arr.filter(function(item, index) {
    return typeof item === 'string' && index < 6;
});

console.log(filteredArr);

You can refer to variables outside the scope of the filter function as well:

var arr1 = [2,4,6,8];
var arr2 = [5,6,7,8];

var filteredArr = arr1.filter(function(item) {
    return arr2.indexOf(item) > -1;
});

console.log(filteredArr);
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Harry Sadler
  • 326
  • 3
  • 7