- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flattening an array with truthy/ falsy values without using library functions - JavaScript
We are required to write a JavaScript array function that takes in a nested array with falsy values and returns an array with all the elements present in the array without any nesting.
For example − If the input is −
const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];
Then the output should be −
const output = [1, 2, 3, 4, 5, false, 6, 5, 8, null, 6];
Example
Following is the code −
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());
Output
This will produce the following output in console −
[ 1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6 ]
- Related Articles
- Finding square root of a number without using library functions - JavaScript
- Finding alphabet from ASCII value without using library functions in JavaScript
- Inserting element at falsy index in an array - JavaScript
- Code to find the center of an array without using ES6 functions - JavaScript
- Array flattening using loops and recursion in JavaScript
- Sorting an array object by property having falsy value - JavaScript
- JavaScript: How to map array values without using "map" method?
- JavaScript: How to Find Min/Max Values Without Math Functions?
- Add number strings without using conversion library methods in JavaScript
- Flattening a deeply nested array of literals in JavaScript
- Sorting or Arranging an Array with standard array values - JavaScript
- Converting number of corresponding string without using library function in JavaScript
- Explain important functions in math.h library functions using C language
- Create new array without impacting values from old array in JavaScript?
- Flattening arrays in JavaScript

Advertisements