Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa số 0 đứng đầu (leading zeros) trong mảng JavaScript

Sử dụng filter() với closure để giữ lại các phần tử từ số khác 0 đầu tiên trở đi.

Ví dụ

const removeLeadingZero = input => 
    input.filter((lastValue => value => lastValue = lastValue || value)(false));

console.log(removeLeadingZero([10, 0, 12, 0, 0]));
console.log(removeLeadingZero([0, 0, 0, 0, 0, 0, 10, 12, 0]));
console.log(removeLeadingZero([12, 0, 0, 1, 0, 0]));

Cách chạy

node demo.js

Kết quả

[ 10, 0, 12, 0, 0 ]
[ 10, 12, 0 ]
[ 12, 0, 0, 1, 0, 0 ]

Giải thích: Closure lastValue ghi nhớ đã gặp số khác 0 chưa. Chỉ bắt đầu giữ giá trị khi lastValue trở thành truthy.

Cách dễ hiểu hơn:

const removeLeadingZeros = arr => {
    let started = false;
    return arr.filter(x => started = started || x !== 0);
};