Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  13] [ 3]  / answers: 1 / hits: 34001  / 9 Years ago, tue, december 22, 2015, 12:00:00

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?


More From » arrays

 Answers
79

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>');




[#63983] Saturday, December 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raynamadilynl

Total Points: 653
Total Questions: 110
Total Answers: 98

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;