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

หาดัชนีของไอเท็มลำดับที่ n ของประเภทหนึ่งในอาร์เรย์ JavaScript


เราต้องเขียนฟังก์ชัน เช่น getIndex() ที่รับอาร์เรย์ arr, สตริง/ตัวเลข txt และตัวเลข n เราต้องคืนค่าดัชนีของการปรากฏครั้งที่ n ของ txt ใน arr, ถ้า txt ไม่ปรากฏ n ครั้ง เราต้องคืนค่า -1

มาเขียนฟังก์ชันสำหรับนี้

ตัวอย่าง

const arr = [45, 76, 54, 43, '|', 54, '|', 1, 66, '-', '|', 34, '|', 5, 76]; const getIndex = (arr, txt, n) => {    const position = arr.reduce((acc, val, ind) => {       if(val === txt){          if(acc.count+1 === n){             acc['index'] = ind;          };          acc['count']++;       }       return acc;    }, {       index: -1,       count: 0    });    return position.index; }; console.log(getIndex(arr, '|', 3)); console.log(getIndex(arr, 54, 2)); console.log(getIndex(arr, '-', 3));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้

10 5 -1