Array Methods
➜ Array methods makes your code look clean and saves you from writing common logic's for lot of Array operations. Array methods make work easy we can get the desired outcome by using simple operations, rather than writing long code.
➜ A JavaScript array is a data structure that allows you to store multiple values in a single variable. There are a lot of array methods In JavaScript, Let's cover few commonly used methods.
➜ JavaScript array methods comes in, when we have to store different data to use when ever required, instead of writing the long lines of code we can use the simple array method to solve complex task into more simple way.
➜ We Will cover 16 JavaScript Array Methods with Examples.
1. splice()
2. slice()
3. reduce()
4. sort()
5. reverse()
6. map()
7. find()
8. every()
9. indexOf()
10. lastIndexOf()
11. toString()
12. findIndex()
13. includes()
14. join()
15. filter()
16. concat()
1. Splice()
What is meaning of splice as per google:
To join the ends of two pieces of film, tape, rope, etc. so that they form one continuous long piece.
same follows with JavaScript Using Splice() method we can add, remove items from the array.
Lets take the array of animals and see how to add new items and remove from the array
syntax :- arr.splice(start[, deleteCount, elem1, ..., elemN])
const animals = ["lion", "tiger", "cheetah"];
animals.splice(0,1,"elephant","monkey");
console.log(animals);
// ["elephant", "monkey", "tiger", "cheetah"]
The first parameter (0) describe where the index of item in the array should start or spliced in.
The second parameter (1) describe how many items should removed from array.
The next parameters describe the new items that are going to add to the array.
If we want to remove the item from array just don't add the new parametes.
const animals = ["lion", "tiger", "cheetah"];
animals.splice(1,1);
console.log(animals);
// ["lion", "cheetah"]
// From the first index delete one item
2. slice()
What is meaning of slice as per google :- A part of something
slice don't delete items from the array. it takes items from the array and forms new array.
slice return a copy of section from the array.
const flowers = ["lotus", "rose", "sunflower", "Daisy", "Tulip"];
const beauty = flowers.slice(1, 3);
console.log(beauty);
// ["rose", "sunflower"]
The slice() select the item from starting index to end index (without including the end index).
3. reduce()
reduce() methods take the two items in the array and reduce it to give output as one value.
const numbers = [26, 42, 64];
const sum = numbers.reduce((prev, current) => prev + current);
console.log(sum) // 132
Here the two parameters are prev & current.
The reduce() method goes through each number in the array. like a loop
When it start the loop (left to right) the number is (26) and the next number to it is (42).
Here the operation is to add, it reduce to the single value by addition.
and each item in the current value changes to the new value as it moves right , till the end of the array and return result as single value.
4. sort()
We will see the difference of sort() in the string as numbers
When we use sort() method to the any array the elements are sorted in ascending order like (A-Z), (0-100).
const words = ["Mango","Apple","Zebra","Ball"];
words.sort();
console.log(words);
// ["Apple", "Ball", "Mango", "Zebra"]
when we use sort() method, based on the first Alphabet it will sort in asceding order.
const numbers = [9,12,48,622];
numbers.sort();
console.log(numbers); // [12, 48, 622, 9]
between 12 and 9 which is smallest number , we know 9 is smallest , but sort() is saying 12 is smallest by comparing the first digit.
const numbers = [9,12,48,622];
numbers.sort(function(a,b) {return (a - b)} );
console.log(numbers);
// A.O - [9, 12, 48, 622]
The function will compare the two values in the array and sort takes place
After sorting if the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, no changes.
const numbers = [9,12,48,622];
numbers.sort(function(a,b) {return (b - a)} );
console.log(numbers);
// D.O - [622, 48, 12, 9]
5.reverse()
The reverse() method takes the array elements present in the first place to the last place and vice versa. It changes the order of array.
const animals = ["lion", "tiger", "cheetah","wolf"];
animals.reverse()
console.log(animals);
// ["wolf", "cheetah", "tiger", "lion"]
6.map()
map() function modify every element in the array and create the new array.
Using map() we can change each and every element in the array can perform any operation like add, sub multiply, divide.
const numbers = [2,3,4,5];
const newArr = numbers.map(multiplyall)
function multiplyall(numbers){
return numbers * 10;
}
console.log(newArr); // [20, 30, 40, 50]
7. find()
find() method provides the first element in the array that satisfy the given test function.
const numbers = [32,19,74,45];
function findnum(numbers){
return numbers > 10
}
console.log(numbers.find(findnum)); // 32
In the above example ,the first value in the array that is greater than 10 is 32 not 19.
because find() methods look what is the first element in the array which is > 10 that's all. It don't care about the second and following elements in the array.
8. every()
every() methods return the Boolean value (either True or False).
every() methods checks the each element in the array.
If the given condition satisfy all the elements in the array it return true.
If any one of them fail to satify it return false.
const age = [14,19,26,22,35,10];
function checkAge(age){
return age > 9
}
console.log(age.every(checkAge)); // true
the condition return true, because In the array every elements is greater than 9, In array if any one of the element is less than array 9 it return false.
9. indexOf()
indexOf() method return the position/index of the element in the given array.
index of the array starts from 0,1,2,3......
const animals = ["lion", "tiger", "cheetah","monkey","elephant"];
let index = animals.indexOf("monkey");
console.log(index); // 3
The index of the monkey in the array is 3.
The index of the first element in the array is 0.
10. lastIndexOf()
If the same element is repeated more than once, and want to find the index of the last one which is repeated multiple times in the array.
const animals = ["lion", "tiger", "lion", "monkey", "elephant", "lion"];
let index = animals.lastIndexOf("lion");
console.log(index); // 5
Here the lion is repeated 3 times, to find the last index of the "lion" we use lastIndexOf() method.
11. toString()
The JavaScript “toString()” method can be utilized to represent an array or a number as a string.
It don't change the original string , it return's the string same as string.
const str = "I am Learning JavaScript Array methods now";
str.toString();
console.log(str);
// I am Learning JavaScript Array methods now
12.findIndex()
The findIndex() method returns position of the index of the first element that satisfy the given condition
const numbers = [12,24,32,46,58,64,77];
function Indexvalue(numbers){
return numbers > 50
}
console.log(numbers.findIndex(Indexvalue)); // 4
In the above array the first index of the element which is greater than 50 is 4.
index of the arrays start from 0.
13.includes()
The includes() returns Boolean value (either true or false)
includes() method check whether the string includes certains value in the given string. For the given array whether the specific entities present or not in that array.
If it contains it returns true, otherwise false.
const arr = "I am Learning JavaScript Array methods now";
const isThere = arr.includes("JavaScript")
console.log(isThere); // true
The value "JavaScript" is included in the given array so it return true. check for "css" it returns false.
14. join()
syntax:- join(separator)
join() method returns new string by joining the all the array object in string which are separated by the (,) or any separator value.
const array = ["Air","Breath","lungs"]
console.log(array.join(" + ")); // Air + Breath + lungs
console.log(array.join(" & ")); // Air & Breath & lungs
console.log(array.join(" 33 ")); // Air 33 Breath 33 lungs
console.log(array.join("")); // AirBreathlungs
15. filter()
filter() method creates array such that it clears/ takedown the part of the array as per the given condition required.
filter() method tests each element of the array and returns the values which are satisfy the given condition.
const age = [12,24,52,16,58,14,77];
function clear(age){
return age > 18
}
console.log(age.filter(clear));
// [24, 52, 58, 77]
Here, using filter() method it filters the age whose above 18.
16.concat()
concat() used to merge two or more arrays.
const arr1 = ["Lion","tiger"];
const arr2 = ["zebra"]
const arr3 = ["kingkong"]
console.log(arr1.concat(arr2, arr3));
// ["Lion", "tiger", "zebra", "kingkong"]
Learn while doing
Thank you ✿
Have a nice day🚀