Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ลบศูนย์นำหน้า (Leading Zeros) ในอาเรย์ JavaScript

ใช้ filter() กรองค่า 0 นำหน้าออก (แต่เก็บ 0 ที่อยู่กลาง/ท้ายไว้)

ตัวอย่างโค้ด

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]));

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo76.js)

ผลลัพธ์

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