i have an array as below.
var array_numbers = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9];
How can all the occurrences of zero be removed from the array and get the non zero numbers in array?
var result_numbers = [1,2,3,4,5,6,7,8,9];
i have an array as below.
var array_numbers = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9];
How can all the occurrences of zero be removed from the array and get the non zero numbers in array?
var result_numbers = [1,2,3,4,5,6,7,8,9];
You can use a Javascript filter function.
First, define a function that will return true if you wish to keep the value or false if you wish to remove it. The value to check will be passed as a parameter to the function.
function removeZeros(value) {
return value !== 0;
}
You can then use that function in the filter
method on your array.
var result_numbers= array_numbers.filter(removeZeros);
Probably easiest to just filter each item through Boolean
:
const arr = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9]
console.log(arr.filter(Boolean))
array_numbers = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9];
for(var x in array_numbers)array_numbers[x] === 0 ? array_numbers.splice(x,1) : 0;
/* See the result */
console.log( JSON.stringify(array_numbers) );
As a complement to Wayne's answer you can also use an ES6 Arrow Function to simplify even further the code.
That would look like this:
var array_numbers = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9];
console.log(array_numbers.filter(x => x !== 0));
And as Rob M stated 0
evaluates to false, so you can trim it down a bit more with just:
array_numbers.filter(x => x);
Example:
var array_numbers = [0,1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9];
console.log(array_numbers.filter(x => x));
Note that in this last case, values that evaluate to false such as false
, ''
, etc would also be removed.