JavaScript Array method sorting (Part 2)

Posted by dr_freak on Thu, 21 Oct 2021 04:21:33 +0200

1. includes()

Method is used to determine whether an array contains a specified value. If so, return   true, otherwise false.

    // arr.includes(searchElement)
    // arr.includes(searchElement, fromIndex)

    /*
        searchElement	must. The element value to find.
        fromIndex	Optional. Search for searchElement starting at this index. If it is negative, the search starts from the index of array.length +fromIndex in ascending order. The default is 0.


        be careful:
            Returns false if fromIndex is greater than or equal to the length of the array. The array will not be searched;
            If fromIndex is negative, the calculated index will be used as the location to start the search for searchElement. If the calculated index is less than 0, the entire array is searched.
    */
    
      let colors = ["red", "pink", "blue", "skyblue"];

      //   Check whether the array contains pink s
      let flag1 = colors.includes("pink");

      //   Detect whether the array contains orange
      let flag2 = colors.includes("orange");

      console.log(flag1); // true
      console.log(flag2); // false

2. indexOf()

Method returns the position of a specified element in the array.

     // array.indexOf(item,start)

      /* 
            item	must. Find the element.
            start	Optional integer parameter. Specifies where to start retrieval in the array. Its legal value is 0 to stringObject.length - 1.
                    If this parameter is omitted, the retrieval will start from the first character of the string.
      */
    
         let colors = ["red", "pink", "blue", "skyblue"];

         // Finds the position of the "pink" element in the colors array
         let pink = colors.indexOf("pink"); 

         console.log(pink); // 1

         // Find the position of "skyblue" in the colors array, starting from the position of index 2
         let skyblue = colors.indexOf("skyblue", 2);

         console.log(skyblue); // 3

3. Array.isArray()

Method is used to determine whether an object is an array. If the object is an array, return   true, otherwise return   false.

    // Array.isArray(obj)
        // obj 	 Required, the object to be judged.

    let arr=[];
    
    // Determine whether it is an array
    console.log(Array.isArray(arr)) // true

4. join()

Method is used to convert all elements in an array into a string.

Elements are separated by a specified separator.

    // array.join(separator)
    /*
        separator:	Optional. Specifies the delimiter to use. If this parameter is omitted, a comma is used as the separator.


         Return value: returns a string. The string is generated by converting each element of arrayObject into a string, connecting these strings, and inserting a separator string between the two elements.
    */
    
    let colors = ["red", "pink", "blue", "skyblue"];

    // The default connection is the array element of colors
    console.log(colors.join()); // red,pink,blue,skyblue

    // Connect colors array elements with "and"
    console.log(colors.join(" and ")); //  and pink and blue and skyblue

5. keys() 

Method is used to create an iteratable object from an array that contains array keys. key containing the original array

Returns true if the object is an array, false otherwise.

    // array.keys() has no parameters
    
    let colors = ["red", "pink", "blue", "skyblue"];
    
    // Create iteration object
    let colorkey = colors.keys();

    console.log(colorkey); // Array Iterator{}

    // Use for...of to iterate out the key of the created iterated object

    for (let item of colorkey) {
      console.log(item); // key
    }

6. lastIndexOf()

Method returns the last position of a specified element in the array, looking forward from the back of the string.

If the element to retrieve does not appear, the method returns - 1.

Tip: if you want to find the position where the array first appears, use the indexOf() method

    // array.lastIndexOf(item,start)
    /*
        item	Required. Specifies the string value to retrieve.
        start	Optional integer parameter. Specifies the location in the string where retrieval begins. Its legal value is 0 to stringObject.length - 1. If this parameter is omitted, the retrieval will begin at the last character of the string.
    
        The start of retrieval is at the start of the array or at the end of the array (when the start parameter is not specified). If an item is found, the return item retrieves the position of the first occurrence in the array from the tail forward. The index start position of the array starts from 0.

        Return value: Nubmer type. If searchvalue exists before the fromindex position in stringObject, it returns the position of the last searchvalue.
    */
    
     let colors = ["red", "pink", "blue", "skyblue", "red", "orange"];
    
     // Find the last index of red in the colors array
     console.log(colors.lastIndexOf("red")); // 4

     // Find the red element starting at index 3
     console.log(colors.lastIndexOf("red", 2)); // 0 is retrieved from index 2 from back to front, so the output is 0

7. map()

Method returns a new array. The elements in the array are the values of the original array elements after calling the function.

The map() method processes the elements in order of the original array elements.

Note: map() does not detect empty arrays.

Note: map() does not change the original array.

    // array.map(function(currentValue,index,arr), thisValue)
    /*
        function(currentValue, index,arr)	must. Function, which is executed by each element in the array
            
            currentValue	must. The value of the current element
            index	        Optional. Index value of the current element
            arr	            Optional. Array object to which the current element belongs

         thisValue: Optional. Object is used when the callback is executed and passed to the function as the value of "this".
                       If this value is omitted, or null and undefined are passed in, this of the callback function is a global object.
    */

    let numbers = [1, 2, 3, 4];

    let newNums = numbers.map(function (currentValue, index, arr) {
        // Returns a new array after the array element * 2
        return currentValue * 2;
    });

    console.log(newNums); // [2, 4, 6, 8]

8. pop()

Method is used to delete the last element of the array and return the deleted element.

Note: this method changes the length of the array!

Tip: to remove the first element of the array, use the shift() method.

    // array.pop() returns the deleted element
    
    let colors = ["red", "pink", "blue", "skyblue","red","orange"];

    // Removes the last bit of the colors array
    let popArr = colors.pop();

    console.log(popArr); // orange

9. push()

Method adds one or more elements to the end of the array and returns a new length.

Note: the new element will be added at the end of the array.

Note: this method changes the length of the array.

Tip: to add an element at the beginning of the array, use the unshift() method.

    // array.push(item1, item2, ..., itemX)
    /*
        item1,item2,...,itemX  must. The element to add to the array
    */

    let colors = ["red", "pink", "blue", "skyblue"];

     // Add an orange element to the colors array
     colors.push("orange");

     console.log(colors); // ["red", "pink", "blue", "skyblue","orange"]

10. reduce()

Method receives a function as an accumulator. Each value in the array (from left to right) is reduced and finally calculated as a value.

reduce() can be used as a high-order function to compose functions.

Note: reduce() does not execute callback functions for empty arrays.

    // array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
    /*
        function(total,currentValue, index,arr)	Required. The function used to execute each array element.
            total	        Required. Initial value, or return value after calculation.
            currentValue	Required. Current element
            currentIndex	Optional. Index of the current element
            arr	            Choose. The array object to which the current element belongs.

         initiaValue   Optional. The initial value passed to the function.
    */


    let numbers = [25, 36, 45, 25, 39];

      // Calculates the sum of the elements of the numbers array
      let result = numbers.reduce(function (total,currentValue,cuurentIndex,arr) {
         return total + currentValue;
      },0);

      console.log(result); // 170

Note: in order to learn more about JavaScript, I sorted out the JavaScript array method. The article is sorted out according to the rookie tutorial. If there is anything wrong, please correct it.

Topics: Javascript Front-end Web Development ECMAScript