In this example, we called the filter() method of the student's array object and passed into an es6 arrow function that tests each element. If functions return true, then the filter() method includes the element in the result array.
Note: filter() method does not change the original array.
The syntax is similar to filter, but find() returns only the first element in an array.
Suppose you need to take an array, transform its elements, and include the results in a new array.
Here the map() method iterate on each element of the numbers array and return a new array with the elements that have been transformed.
Suggestion: If you don’t actually need the array and you are simply trying to iterate, use forEach(). Remember map will create a new array on each call.
The slice() is used to clone an array as shown in the following example:
Here, the newNum array contains all the elements of the numbers array.
The slice() method accepts two optional parameters as follows:
slice(start, stop). This method with optional parameters returns a new array with specified start to end elements.
Suppose that you have an array of numbers, like this:
let numbers = [1, 2, 3, 4, 5];
If you call array.reduce() that helps you to reduce an array to a single value, like this:
Now the million-dollar question is how exactly it works? well, The reduce() method take 4 arguments:
- currentValue(The value of the array element in the current iteration)
- currentIndex(The index of the array element in the current iteration)
Here, currentIndex and array are the optional arguments. In the above example, total = accumulator, by default it's 0. And in every iteration current value is changed. So for Now the total= 0 and currentNumber= 1.
So the final output is 21. You can change the initial value.
Here we set the initial value is 4, so in this case, total= 4 and currentNumber= 1, and the output is 10.