Example arrays:
[0, 0, 0, 14, 0, 63, 0]
[243, 0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0]
[0]
Wanted arrays:
[14, 0, 63, 0]
[243, 0, 0, 0, 1]
[1, 0]
[]
[]
I tried using filter method .filter(val => val) but it remove all zeros from array.
This is all you need.
const arr = [0, 0, 0, 14, 0, 63, 0];
while (arr.indexOf(0) === 0) {
arr.shift()
}
console.log(arr)
Extract to a function
function leftTrim(array, trimBy = 0) {
// prevents mutation of original array
const _array = [...array];
while (_array.indexOf(trimBy) === 0) {
_array.shift()
}
return _array;
}
// trim left by 0 (default)
console.log(leftTrim([0, 0, 1, 0, 1, 0]));
// trim left by 1
console.log(leftTrim([1, 1, 1, 1, 0, 1, 0], 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With