Page 116 - JavaScript
P. 116

From ES5.1 onwards, you can use the native method Array.prototype.filter to loop through an
        array and leave only entries that pass a given callback function.


        In the following example, our callback checks if the given value occurs in the array. If it does, it is a
        duplicate and will not be copied to the resulting array.

        5.1


         var uniqueArray = ['a', 1, 'a', 2, '1', 1].filter(function(value, index, self) {
           return self.indexOf(value) === index;
         }); // returns ['a', 1, 2, '1']


        If your environment supports ES6, you can also use the Set object. This object lets you store
        unique values of any type, whether primitive values or object references:


        6

         var uniqueArray = [... new Set(['a', 1, 'a', 2, '1', 1])];


        See also the following anwsers on SO:


            •  Related SO answer
            •  Related answer with ES6

        Removing all elements



         var arr = [1, 2, 3, 4];


        Method 1


        Creates a new array and overwrites the existing array reference with a new one.


         arr = [];


        Care must be taken as this does not remove any items from the original array. The array may
        have been closed over when passed to a function. The array will remain in memory for the life of
        the function though you may not be aware of this. This is a common source of memory leaks.


        Example of a memory leak resulting from bad array clearing:


         var count = 0;

         function addListener(arr) { // arr is closed over
           var b = document.body.querySelector("#foo" + (count++));
           b.addEventListener("click", function(e) { // this functions reference keeps
             // the closure current while the
             // event is active
             // do something but does not need arr
           });
         }




        https://riptutorial.com/                                                                               73
   111   112   113   114   115   116   117   118   119   120   121