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

ความถี่ของสมาชิกที่น้อยกว่าและมากกว่าค่าที่กำหนด - JavaScript

สมมติว่าเรามีอาร์เรย์:

const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];

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

ตัวอย่าง

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

const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];

const smallerLargerNumbers = (arr, num) => {
  return arr.reduce((acc, val) => {
    let { greater, smaller } = acc;
    if(val > num){
      greater++;
    };
    if(val < num){
      smaller++;
    };
    return { greater, smaller };
  }, {
    greater: 0,
    smaller: 0
  });
};

console.log(smallerLargerNumbers(arr, 3));

ผลลัพธ์

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

{ greater: 8, smaller: 1 }