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

นับจำนวนสระและพยัญชนะ - JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีตัวอักษรอังกฤษ เช่น:

const str = 'This is a sample string, will be used to collect some data';

ฟังก์ชันควรคืนค่าอ็อบเจกต์ที่มีจำนวนสระและพยัญชนะในสตริง:

{ vowels: 17, consonants: 29 }

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const str = 'This is a sample string, will be used to collect some data';

const countAlpha = str => {
  return str.split('').reduce((acc, val) => {
    const legend = 'aeiou';
    let { vowels, consonants } = acc;
    if(val.toLowerCase() === val.toUpperCase()){
      return acc;
    };
    if(legend.includes(val.toLowerCase())){
      vowels++;
    }else{
      consonants++;
    };
    return { vowels, consonants };
  }, {
    vowels: 0,
    consonants: 0
  });
};

console.log(countAlpha(str));

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

{ vowels: 17, consonants: 29 }