हमें एक JavaScript सरणी फ़ंक्शन लिखना होगा जो एक नेस्टेड सरणी लेता है जिसमें false मान भी होते हैं और एक सरणी लौटाता है जिसमें सरणी में मौजूद सभी तत्व बिना किसी नेस्टिंग के होते हैं।
उदाहरण के लिए: यदि इनपुट है:
const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
तब आउटपुट होना चाहिए:
const output = [1, 2, 3, 4, 5, false, 6, 5, 8, null, 6];
इसलिए, आइए इस फ़ंक्शन के लिए कोड लिखते हैं:
उदाहरण
इसका कोड निम्नलिखित होगा:
const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [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());
आउटपुट
कंसोल में आउटपुट होगा:
[ 1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6 ]