मान लीजिए, हमारे पास फ्रेज़ेज़ का एक रेफरेंस ऐरे है:
const reference = ["your", "majesty", "they", "are", "ready"];
और हमें ऊपर के ऐरे के कुछ एलिमेंट्स को दूसरे ऐरे के आधार पर जोड़ना है। यदि दूसरा ऐरे यह है:
const another = ["your", "they are"];
तो परिणाम ऐसा होगा:
result = ["your", "majesty", "they are", "ready"];
यहां, हमने दोनों ऐरे के एलिमेंट्स की तुलना की, हमने पहले ऐरे के एलिमेंट्स को जोड़ा यदि वे दूसरे ऐरे में एक साथ मौजूद थे।
हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसे दो ऐरे लेता है और एक नया जोड़ा हुआ ऐरे लौटाता है।
उदाहरण
const reference = ["your", "majesty", "they", "are", "ready"]; const another = ["your", "they are"]; const joinByReference = (reference = [], another = []) => { const res = []; const filtered = another.filter(a => a.split(" ").length > 1); while(filtered.length) { let anoWords = filtered.shift(); let len = anoWords.split(" ").length; while(reference.length>len) { let refWords = reference.slice(0,len).join(" "); if (refWords == anoWords) { res.push(refWords); reference = reference.slice(len,reference.length); break; }; res.push(reference.shift()); }; }; return [...res, ...reference]; }; console.log(joinByReference(reference, another));आउटपुट
इससे निम्नलिखित आउटपुट प्राप्त होगा:
[ 'your', 'majesty', 'they are', 'ready' ]