Page 109 - JavaScript
P. 109

function deepReverse(arr) {
           arr.reverse().forEach(elem => {
             if(Array.isArray(elem)) {
               deepReverse(elem);
             }
           });
           return arr;
         }


        Example for deepReverse:


         var arr = [1, 2, 3, [1, 2, 3, ['a', 'b', 'c']]];

         deepReverse(arr);


        Results in:


         arr // -> [[['c','b','a'], 3, 2, 1], 3, 2, 1]


        Remove value from array


        When you need to remove a specific value from an array, you can use the following one-liner to
        create a copy array without the given value:


         array.filter(function(val) { return val !== to_remove; });


        Or if you want to change the array itself without creating a copy (for example if you write a function
        that get an array as a function and manipulates it) you can use this snippet:


         while(index = array.indexOf(3) !== -1) { array.splice(index, 1); }


        And if you need to remove just the first value found, remove the while loop:


         var index = array.indexOf(to_remove);
         if(index !== -1) { array.splice(index , 1); }


        Checking if an object is an Array


        Array.isArray(obj) returns true if the object is an Array, otherwise false.


         Array.isArray([])           // true
         Array.isArray([1, 2, 3])    // true
         Array.isArray({})           // false
         Array.isArray(1)            // false


        In most cases you can instanceof to check if an object is an Array.


         [] instanceof Array; // true
         {} instanceof Array; // false




        https://riptutorial.com/                                                                               66
   104   105   106   107   108   109   110   111   112   113   114