เราต้องเขียนฟังก์ชันที่รับสตริงและสลับคำติดกันของสตринั้นกันและกันจนจบสตริง
ตัวอย่าง
โค้ดสำหรับนี้:
const str = "This is a sample string only"; const replaceWords = str => { return str.split(" ").reduce((acc, val, ind, arr) => { if(ind % 2 === 1){ return acc; } acc += ((arr[ind+1] || "") + " " + val + " "); return acc; }, ""); }; console.log(replaceWords(str));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
is This sample a only string