เราต้องเขียนฟังก์ชันโดยบอกว่า findPositions() ที่รับอาร์เรย์สองอาร์เรย์เป็นอาร์กิวเมนต์ และควรส่งคืนอาร์เรย์ของดัชนีขององค์ประกอบทั้งหมดของอาร์เรย์ที่สองที่มีอยู่ในอาร์เรย์แรก
ตัวอย่างเช่น −
If the first array is [‘john’, ‘doe’, ‘chris’, ‘snow’, ‘john’, ‘chris’], And the second array is [‘john’, chris]
จากนั้นผลลัพธ์ควรเป็น −
[0, 2, 4, 5]
ดังนั้น มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน เราจะใช้ forEach() วนซ้ำที่นี่
ตัวอย่าง
const values = ['michael', 'jordan', 'jackson', 'michael', 'usain',
'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositions = (first, second) => {
const indicies = [];
first.forEach((element, index) => {
if(second.includes(element)){
indicies.push(index);
};
});
return indicies;
};
console.log(findPositions(values, queries)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
[ 0, 2, 3, 5, 6, 7 ]