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]
- var t = [1,2.3,5,null,"",undefined,"hello","v","C#"]
- t.filter(Boolean)
-
- t.filter(Number)
- [1, 2.3, 5]
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.
- [[[0], [1]], [[2], [3]], [[4], [5]]].toString().split(",").map(Number)
-
-
-
- [[[0], [1]], [[2], [3]], [[4], [5]]].toString().split(",")
- ["0", "1", "2", "3", "4", "5"]
-
- [[[["asfdsadf"]]],["test"]].toString().split(",")
- ["asfdsadf", "test"]
-
- [].concat.apply([], [3,4,4,[4],[5],[7]);
-
-
- var testSingleNestedArr = [["d"],[4],["Hello"]]
- [].concat.apply([],testSingleNestedArr)
- ["d", 4, "Hello"]
the chanllege comes only if the nested array is more nested
- function faltTheArr(arr) {
- return arr.reduce(function (acc, cur) {
- return acc.concat(Array.isArray(cur) ? faltTheArr(cur) : cur);
- }, []);
- }
-
- faltTheArr([[[1,[2.2]],3,4,5], [6,4,5]]);
Creating custom Array function clear()
- Array.prototype.clear = function() {
- var i;
- var clearedAr = [];
- for (i = 0; i < this.length; i++) {
- if(this[i]){
- clearedAr.push(this[i]);
- }
-
- }
- console.log(clearedAr.filter(Boolean).length);
- return clearedAr.filter(Boolean);
- };
-
- var Arr= ["Banana", "Orange", "Apple", "Mango",null,undefined,""];
- Arr = Arr.clear();
-