हमें एक फ़ंक्शन लिखना है, मान लीजिए findPositions() जो दो एरे को आर्गुमेंट के रूप में लेता है। और यह दूसरे एरे के सभी तत्वों के इंडेक्स का एक एरे लौटाना चाहिए जो पहले एरे में मौजूद हैं।
उदाहरण के लिए -
यदि पहला एरे है ['john', 'doe', 'chris', 'snow', 'john', 'chris'], और दूसरा एरे है ['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 ]