Reputation: 1131
var numbers = [1,2,0,3,0,4,0,5];
If I have the above array and I want to remove the 0s and output an array of [1,2,3,4,5] how would I do it?
I have the below code but I am getting an "TypeError: arr.includes is not a function" error...
var zero = 0;
var x = balDiffs.map(function(arr, i) {
console.log(arr);
if(arr.includes(zero)) {
return i;
}
});
Upvotes: 0
Views: 97
Reputation: 386654
Array#map
returns an array with the same length as the given array, but it can change the values of each element.
Then you took an element for Array#includes
or String#includes
but that does not work with numbers.
But even if that works, you would get only zeroes and undefined
with the given approach.
You could use Array#filter
and filter the unwanted value.
var numbers = [1, 2, 0, 3, 0, 4, 0, 5],
value = 0, // or any other value
filtered = numbers.filter(v => v !== value);
console.log(filtered);
Approach with more than one unwanted value.
var numbers = [1, 2, 0, 3, 0, 4, 0, 5],
unwanted = [0, 3],
filtered = numbers.filter(v => !unwanted.includes(v));
console.log(filtered);
Upvotes: 3
Reputation: 191996
Use Array#filter with Boolean function as the callback. The Boolean function will return false
for 0, and true
for other numbers:
var numbers = [1,2,0,3,0,4,0,5];
var result = numbers.filter(Boolean);
console.log(result);
Upvotes: 3