let arr = new Array();
let arr = 
Both methods does the same thing, however, for execution speed, simplicity and readability, use the second method(the array literal method).
we’ll use the following array in our examples:
This is an array that holds an object at each index,
The filter() method creates a new array containing all the elements that passes the test implemented by the callback function provided in the filter() method. Let’s take a look.
Inside the callback function, the
ticketPrice of each array element in checked to see if it is less than 100. If the callback function returns
true then this element is added to the new array.
With the map() method a function is called once for each element in the array. The results from the function called is used to create a new array.
The map() method can be useful when you want to create a new array using values from an existing array or you want to extract specific values from within an array.
Let’s say we want to get the name of every movie. We’d do the following.
Inside the callback function which is executed for each element in the movies array, we return the name of the movie found at each element. This is then stored inside the
The find() method returns the value of the first element in an array that passes a test (provided as a function[callback]).
What if we wanted the information for the movie Queen & Slim? We’d do the following.
The find() method will return the value of the first array element that the callback function returns a true value for. Once a true value is returned, it does not check the remaining elements within the array.
forEach() method works similarly to a for-loop and can be used instead of a for-loop. A function is called once for each element of the array. You can then perform any kind of operation on the elements of the given array. The forEach() method is different from the previous methods in that it does not create a new array.
Let’s loop through the movies array and print the name of each movie.
Using the forEach() method makes it much easier and cleaner to loop through an array.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value which is stored in an accumulator.
What if we wanted to calculate the total of all movie ticket price (ticketPrice)? You could loop through the array using a for-loop or a forEach() and sum the ticketPrice of all element in the array. However, you could do this in a much easier way using the reduce() method.
This is how it is done.
The reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
0 is the initial value given to the
Thanks for reading! Until next time, Think, Learn, Create, Repeat!