Page 114 - JavaScript
P. 114

var values = [1, 2, 3, 4, 5, 3];
         var i = values.indexOf(3);
         if (i >= 0) {
           values.splice(i, 1);
         }
         // [1, 2, 4, 5, 3]


        The splice() method can also be used to add elements to an array. In this example, we will insert
        the numbers 6, 7, and 8 to the end of the array.


         var values = [1, 2, 4, 5, 3];
         var i = values.length + 1;
         values.splice(i, 0, 6, 7, 8);
         //[1, 2, 4, 5, 3, 6, 7, 8]


        The first argument of the splice() method is the index at which to remove/insert elements. The
        second argument is the number of elements to remove. The third argument and onwards are the
        values to insert into the array.


        Array comparison


        For simple array comparison you can use JSON stringify and compare the output strings:


         JSON.stringify(array1) === JSON.stringify(array2)


              Note: that this will only work if both objects are JSON serializable and do not contain
              cyclic references. It may throw TypeError: Converting circular structure to JSON


        You can use a recursive function to compare arrays.


         function compareArrays(array1, array2) {
           var i, isA1, isA2;
           isA1 = Array.isArray(array1);
           isA2 = Array.isArray(array2);

           if (isA1 !== isA2) { // is one an array and the other not?
             return false;      // yes then can not be the same
           }
           if (! (isA1 && isA2)) {      // Are both not arrays
             return array1 === array2;  // return strict equality
           }
           if (array1.length !== array2.length) { // if lengths differ then can not be the same
             return false;
           }
           // iterate arrays and compare them
           for (i = 0; i < array1.length; i += 1) {
             if (!compareArrays(array1[i], array2[i])) { // Do items compare recursively
               return false;
             }
           }
           return true; // must be equal
         }


        WARNING: Using the above function is dangerous and should be wrapped in a try catch if you



        https://riptutorial.com/                                                                               71
   109   110   111   112   113   114   115   116   117   118   119