4

It seems correct for me, but it doesn't work:

var arr = [1, 2, 3, 4, 5];

var bar = [2, 4];

arr = arr.filter(function(v) {
  for (var i; i < bar.length; i++) {
    return bar.indexOf(v);
  }
});

console.log(arr); // []

// expected: [1, 3, 5]

How this will work, and how to do the same work with map?

1
  • 1
    Where are you using i ? Commented Dec 22, 2015 at 5:36

1 Answer 1

12

Array#filter iterates over the array, you don't need for inside filter

The problem with for inside filter is that it'll return the index of the element, which could be -1(truthy) if not found and anything upto the length of array. And only for the first element i.e. index zero, filter will not add the element as zero is falsey in JavaScript.

Also, the for loop will only check if the first element of the bar and return from there.

var arr = [1, 2, 3, 4, 5];
var bar = [2, 4];

arr = arr.filter(function(v) {
  return bar.indexOf(v) === -1;
});

console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');


You don't need Array#map, map will transform the array elements with keeping the same number of elements.


ES6:

Since ES6 you can use Array#includes, and arrow functions to make your code look cleaner:

let arr = [1, 2, 3, 4, 5];
let bar = [2, 4];

arr = arr.filter(v => !bar.includes(v));

console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

4 Comments

Agree with answer. To answer the question of filter and map, filter returns only those elements if the return value in the function is true. Map returns same number of elements, for the return of false value, the element returned would be undefined. One more thing, the map return a new array. Filter does not return a new array.
@Tushar Can you give me the map example for the same result, just for showcase?
If used map instead of filter, you need to use filter after map to remove holes Demo @elkebirmed
ES6: arr.filter(e => !bar.includes(e))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.