JavaScript Array.filter not working as expected
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>');
elkebirmed
I'm a Full-stack web developer and a Graphic designer. I'm currently focused on: - Laravel framework - Wordpress - Web design - Node.js - Vue.js - Graphic design
Updated on September 21, 2020Comments
-
elkebirmed over 3 years
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?