Array Iterator Method

Keywords: Javascript Algorithm

This counting method is primarily used to iterate over array objects, which in turn pass each element of the array to the functions we provide to facilitate iteration, mapping, filtering, testing, and merging of the array.

Before talking about these methods, let's first understand that all of them accept a function as their first argument and call this function once for each element (or some element) of the array. If the array is sparse, the incoming function will not be called on an array element that does not exist. In most cases, the function we provide will be called with three parameters: the value of the array element, the index of the array element, and the array element itself. In most cases, we only need the first parameter, and we can ignore the second and third parameters. Most of the following methods accept an optional second parameter. If you specify this parameter, the first function will be called as if it were the second parameter. In other words, the second parameter we pass in will become the this value inside the function passed in as the first parameter. The return value of the incoming function is usually unimportant. However, different methods deal with this return value in different ways. The methods described here will not modify the array that calls them (however, incoming functions may modify this array)

1.forEach()

The forEach() method iterates over each element of the array and executes the function we specify for each element of the array. The first parameter passed in by the traditional forEach() method is a function. ForEach() passes three parameters to the function when it is called, the value of the array element, the index value of the array, and the array itself if we only need to manipulate the value of the array element. You only need to pass one parameter. The sample code is as follows:

<script>
      let data = [1, 2, 3, 4, 5];
      // Define an index array in literal form
      let sum = 0;
      // Initialize a variable to hold the sum they add
      data.forEach((value) => {
        // The forEach() method of the array is called with the value in arrow function parentheses being each value in the array
        sum += value;
        // Operate their sum
      });
      console.log(sum);
      // Console output found to be 15
    </script>
 <script>
      let data = [1, 2, 3, 4, 5];
      // Define an index array in literal form
      data.forEach(function (v, i, a) {
        // The parameters inside the loop using forEach() are v for each parameter i in the array and subscript a for the array itself
        a[i] = v + 1; // You can also write ++ v here
        // Each element of the array is + 1 and returned to the original array
      });
      console.log(data);
      // The output shows that each element of the array is + 1
    </script>

It is important to note that forEach() does not provide a way to iterate ahead of time, in other words, there is no equivalent mechanism for break statements as in a regular for loop.

2. The map() method passes each element of the array that calls it to the function we specify, returning an array of returned values from the function as follows:

 <script>
      let a = [1, 2, 3];
      let b = a.map((x) => x * x);
      // We need a variable to accept that the return value after the map function is processed is an array
      console.log(b);
      // Outputting this array shows that each element of the array is equally symmetrical
    </script>

The function passed to map () is called in the same way as the function passed to forEach(). However, for the map() method, the function we passed in should return a value, noting that map() returns a new array and does not modify the array that calls it. If the array is sparse, the missing elements will not call our function, but the returned array will be as sparse, the same length, and the missing elements will be the same.

3. The filter() method returns an array that contains a subarray of the array that calls it. The function passed to this method should be an assertion function, that is, a function that returns true or false. This function space is called just like the function passed to forEach() and map(). If the function returns true or if the return value is converted to true, then the element passed to the function is the member of the subarray that filter() eventually returns as follows:

<script>
      let a = [5, 4, 3, 2, 1];
      let b = a.filter((x) => x < 3);
      // The expression here writes the condition that if true a new array is generated and saved in variable b
      let c = a.filter((x, i) => i % 2 === 0);
      // The expression here writes the condition that if true a new array is generated and saved in variable b
      console.log(a);
      console.log(b);
      console.log(c);
    </script>

One thing to note is that filter() skips missing elements in a sparse array and returns an array that is always dense, so you can use one of the following methods to clear the gaps in a sparse array and make it dense. Examples are as follows:

<script>
      let a = [1, , , null, , 2, 3, 4, 5];
      let b = a.filter((a) => true);
      console.log(b);
      // The condition here is that if there is a value it will be added to the new array and if there is no value it will be skipped
      // If you want to both clean up the gaps and delete elements with undefined and null values, you can write like this
      let c = a.filter((x) => x !== undefined && x !== null);
      console.log(c);
    </script>

4.The find() and findIndex() methods are similar to filter(), in that they are both filtered arrays, looking for elements whose assertion function returns positive values, but unlike filter(), they stop iterating when the assertion function finds the first element, in which case find () returns the matching element, findIndex () returns the index of the matching element, and if no matching element is found, Find() returns undefined, while findIndex() returns -1 as follows:

<script>
      let a = [1, 2, 3, 4, 5];
      console.log(a.findIndex((x) => x === 3));
      // Find elements with an index value of 3
      console.log(a.findIndex((x) => x < 0));
      // Find element values with index values less than 0 Index values start at 0 so return -1
      console.log(a.findIndex((x) => x % 5 === 0));
      // Finding an index value that can take the remaining 5 to 0 only assumes 5 to be 4
      console.log(a.findIndex((x) => x % 7 === 0));
      // Find an index value that can take the remaining 7 to 0 values
    </script>

5.every() and some() methods are array assertion methods, that is, they call our incoming assertion function on an array element and return true or false

The some() method is similar to the mathematic Whole Range quantifier from in that it returns true only when the assertion function returns true for all elements of the array, as shown in the following example:

<script>
      let a = [1, 2, 3, 4, 5];
      console.log(a.every((x) => x < 10));
      console.log(a.every((x) => x % 2 === 0));
      // The biggest difference between every() and filter() is that if the conditions in the specified function are met in filter(), it generates a new array.
      // In every() all values must satisfy the conditions of the specified function to return true or false
    </script>

An example of the use of some() function is as follows:

<script>
      /**
       * some()The method is similar to the Existence quantifier on an array ʒ, An assertion function returns true as long as one of the array elements returns true, but only if all the elements of the array return false for the assertion function
       * Return false
       */
      let b = [1, 2, 3, 4, 5];
      let r = b.some((x) => x % 2 === 0);
      console.log(r);
      // true b This array contains even numbers
      console.log(b.some(isNaN));
      // There is no non-number ed value in the falseb array
    </script>

Note: every () and some () both stop iterating over arrays when they know what value to return, some () returns true the first time an assertion function returns true, and only when all assertions return false. Every() on the contrary, he returns false the first time the assertion function returns false, traverses the array only when all the assertion functions return true, and note that if you call them on an empty array, every() returns true and some() returns false, according to the mathematical tradition.

6.reduce() and reduce Right()

The reduce() and reduce Right() methods use the functions we specify to merge the array elements, resulting in a value, which is a common operation in function programming, sometimes referred to as injection or fold. Examples are as follows:

 <script>
      let a = [1, 2, 3, 4, 5];
      console.log(a.reduce((x, y) => x + y, 0));
      // Sum of all values
      console.log(a.reduce((x, y) => x * y, 1));
      // Product of all values
      console.log(a.reduce((x, y) => (x > y ? x : y)));
      // Find a Maximum
    </script>

redcue() accepts two parameters. The first parameter is the function that performs the merge operation. The task of this merge function is to merge or combine two values into a single value and return this value. In the example above, the merge function merges two values by adding them together, multiplying them and selecting the maximum value. The second parameter is optional and is the initial value passed to the merge function.

Posted by arnoldd99 on Mon, 06 Dec 2021 09:50:13 -0800