ARRAY METHODS
What are Arrays?
An array is a special variable, which can hold more than one value. An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax :
1 const array_name = [item1, item2, ...];
2 const cars = ["Saab", "Volvo", "BMW"];
Array Methods
JavaScript provides a number of built-in methods for manipulating arrays. Some of the most commonly used array methods are:
length
This method returns the number of elements in an array. For example, the following code will return 3:
1var myArray = [1, "Hello", [2, 3]];
2console.log(myArray.length);
push
This method is used to add an element to the end of an array. For example, the following code will add the element "World" to the end of the array:
1var myArray = [1, "Hello", [2, 3]];
2myArray.push("World");
3console.log(myArray); // [1, "Hello", [2, 3], "World"]
forEach()
forEach() function in js helps to loop through the array without creating a new array . It takes a call back function as arguments.
1let num = [1, 2, 3, 4, 5];
2num.forEach((value, index, array) => {
3 console.log(value, index, array);
4});
map():
map() function returns the new array of same length. It takes a call back function as arguments.
1let sq = num.map((value) => {
2 return value * value;
3});
4console.log(sq);
filter()
.filter() function returns the the new array but can be of different length. It also takes call back function as arguments.
1let even = arr.filter((item) => item % 2 == 0);
2console.log(even)
3//this returns the number those are even
reduce()
reduce() function returns a single value by performing a given calculation on its preceding value.
1let sum = num.reduce((acc, value, index, array) => {
2 return acc + value;
3});
4console.log(sum);