हमें एक JavaScript सरणी फ़ंक्शन लिखना है जो एक नेस्टेड सरणी लेता है और सभी तत्वों के साथ एक सरणी लौटाता है जिसमें कोई नेस्टिंग न हो।
उदाहरण के लिए:
// यदि इनपुट है: const arr = [[1, 2, 3], [4, 5], [6]]; // तो आउटपुट होना चाहिए: const output = [1, 2, 3, 4, 5, 6];
आइए इस फ़ंक्शन के लिए कोड लिखते हैं:
विधि 1: पुनरावृत्ति का उपयोग करके
यहाँ हम मूल नेस्टेड सरणी पर लूप करेंगे और नेस्टेड तत्वों को पुनरावर्ती रूप से एक नई सरणी में डालेंगे।
उदाहरण
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function() {
let res = [];
for (let i = 0; i < this.length; i++) {
if (Array.isArray(this[i])) {
res.push(...this[i].flatten());
} else {
res.push(this[i]);
}
}
return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
विधि 2: Array.prototype.reduce() का उपयोग करके
यहाँ हम reduce() मेथड का उपयोग करके एक नई सरणी का निर्माण करेंगे:
उदाहरण
const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function() {
return this.reduce((acc, val) => {
return acc.concat(...val);
}, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());
आउटपुट
दोनों विधियों के लिए कंसोल आउटपुट होगा:
[ 1, 2, 3, 4, 5, 6 ]