สมมติว่าเรามีอาร์เรย์ของสตริงเช่นนี้ −
const arr = [ 'iLoveProgramming', 'thisisalsoastrig', 'Javascriptisfun', 'helloworld', 'canIBeTheLongest', 'Laststring' ];
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์สตริงดังกล่าว จุดประสงค์ของฟังก์ชันของเราคือการเลือกสตริงที่ยาวที่สุดทั้งหมด (หากมีมากกว่าหนึ่ง)
ในที่สุด ฟังก์ชันควรส่งคืนอาร์เรย์ของสตริงที่ยาวที่สุดในอาร์เรย์
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [
'iLoveProgramming',
'thisisalsoastrig',
'Javascriptisfun',
'helloworld',
'canIBeTheLongest',
'Laststring'
];
const getLongestStrings = (arr = []) => {
return arr.reduce((acc, val, ind) => {
if (!ind || acc[0].length < val.length) {
return [val];
}
if (acc[0].length === val.length) {
acc.push(val);
}
return acc;
}, []);
};
console.log(getLongestStrings(arr)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
[ 'iLoveProgramming', 'thisisalsoastrig', 'canIBeTheLongest' ]