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

การหาสตริงที่ยาวที่สุดทั้งหมดจากอาร์เรย์ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์สตริง คืนอาร์เรย์ของสตริงที่มีความยาวมากที่สุด (ถ้ามีหลายสตริงยาวเท่ากัน ให้คืนทั้งหมด)

ตัวอย่าง: ['iLoveProgramming', 'thisisalsoastrig', 'Javascriptisfun', 'helloworld', 'canIBeTheLongest', 'Laststring'] → ['iLoveProgramming', 'thisisalsoastrig', 'canIBeTheLongest']

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

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' ]