Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array.filter not working as expected

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?

like image 338
elkebirmed Avatar asked Oct 28 '25 19:10

elkebirmed


1 Answers

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>');
like image 52
Tushar Avatar answered Oct 31 '25 10:10

Tushar