Clearing A Array And Reduce Array Elements, Flatten The Nested Array

Many times while developing, we face issue in clearning the return objects or Array, This ariticles deals with clearing junk values,removing null,undefined or creating a custom "Array" function to do all.
 
Best way to get any filter values from Array of any particular data type is to use filter method [especially Number and truthy/falsely value] 
  1. var t = [1,2.3,5,null,"",undefined,"hello","v","C#"]  
  2. t.filter(Boolean) // Output will be [1, 2.3, 5, "hello", "v", "C#"]  
  3.   
  4. t.filter(Number)  
  5. [1, 2.3, 5] //Output with just Number datatype  
Working with Nested Arrays, it is always easy to working in numbers rather than string type.One of fastest way to reduce nested array is to convert to string value and use split operator. 
  1. [[[0], [1]], [[2], [3]], [[4], [5]]].toString().split(",").map(Number)  
  2. // Output will be [1, 2, 3, 4, 5]  it will be typeof Number    

  3. //When output is needed to be in String the split operation itself suffice  
  4.   
  5. [[[0], [1]], [[2], [3]], [[4], [5]]].toString().split(",")  
  6. ["0""1""2""3""4""5"// Output in string format  
  7.   
  8. [[[["asfdsadf"]]],["test"]].toString().split(",")  
  9. ["asfdsadf""test"// Result  
  10.   
  11. [].concat.apply([], [3,4,4,[4],[5],[7]);  
  12. //[3,4,4,4,5,7] Output it works well for single nested array  
  13.   
  14. var testSingleNestedArr = [["d"],[4],["Hello"]]  
  15. [].concat.apply([],testSingleNestedArr)
  16. ["d", 4, "Hello"// Without changing the datatype   
the chanllege comes only if the nested array is more nested
  1. function faltTheArr(arr) {  
  2.     return arr.reduce(function (acc, cur) {  
  3.         return acc.concat(Array.isArray(cur) ? faltTheArr(cur) : cur);  
  4.     }, []);  
  5. }  
  6.   
  7. faltTheArr([[[1,[2.2]],3,4,5], [6,4,5]]); // [1, 2.2, 3, 4, 5, 6, 4, 5]   
Creating custom Array function clear() 
  1. Array.prototype.clear = function() {  
  2.     var i;  
  3.     var clearedAr = [];  
  4.     for (i = 0; i < this.length; i++) {  
  5.     if(this[i]){  
  6.         clearedAr.push(this[i]);  
  7.         }  
  8.           
  9.     }  
  10.    console.log(clearedAr.filter(Boolean).length); // output 4  
  11.     return clearedAr.filter(Boolean);  
  12. };  
  13.   
  14. var Arr= ["Banana""Orange""Apple""Mango",null,undefined,""];  
  15.  Arr =  Arr.clear();  
  16. // Value of Arr  ["Banana", "Orange", "Apple", "Mango"]  
Ebook Download
View all
Learn
View all