Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros in array

Tags:

javascript

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.

like image 251
ledowep Avatar asked Feb 16 '26 23:02

ledowep


1 Answers

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));
like image 173
Kharel Avatar answered Feb 19 '26 12:02

Kharel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!