About Array and It's all Method
In the given article, you will learn about the JavaScript Array methods with the help of examples.
Table of contents
- Array?
- Array Methods
- Insert method inside an array
- 1:- Push Method arrayName.push()
- 2:- Slice Method arrayName.slice( )
- 3:- Splice Method arrayName.splice( )
- 4:- concat Method arrayName.concat( )
- 5:- fill Method arrayName.fill( )
- 6:- includes Method arrayName.includes( )
- 7:- indexOf Method arrayName.indexOf( )
- 8:- isArray Method arrayName.isArray( )
- 9:- join Method arrayName.isArray( )
- 10:- lastIndexOf Method arrayName.lastIndexOf( )
- 11:- map Method arrayName.map( )
- 12:- pop Method arrayName.pop( )
- 13:- reverse Method arrayName.reverse( )
- 14:- shift Method arrayName.shift( )
- 15:- unshift Method arrayName.unshift( )
- 16:- sort Method arrayName.sort( )
- 17:- split Method arrayName.split( )
- 18:- for of Method
- 19:- break and continue
Array?
The array is just like a variable, in a variable we can store only one value but in the array, we can store multiple values and many types of data.
1- Declaration of the Array
We declare the array as like a variable but here is the main change in syntax, we use after the equal sign write square brackets and inside the brackets, we write the different data type elements.
- There are two ways to declare the array. The first one is recommended for declaring the array.
```javascript
// Recomended
//This is first way of declaration
let arrayName = ["Atul", "Singh", "FSJS", 1, 2, 1234, true];
```
- The second way to declare an array
//Not Recomended
//This is second way of declaration
let arrayName = new Array("Atul", "Singh", "FSJS", 1, 2, 1234, true);
- The array has an Index number
An array has an index number is always starts from zero and goes on the length of the element ever you write. Inside the array, every element has a unique index no which we have to get particular elements by this index no.
//Index number always start from zero
let myArray = ["Atul", "Singh", "FSJS", 1, 2, 1234, true];
console.log(myArray[0]);
console.log(myArray[1]);
console.log(myArray[2]);
console.log(myArray[3]);
console.log(myArray[5]);
ok now we go to talk about the Array Method
Array Methods
Insert method inside an array
1:- Push Method arrayName.push()
The push method inserts the element inside the existing array in the last of the older present elements and index no starts from their next number to inserted elements.
The push method modified the original array and give us the new array.
let myArray = ["Atul", "Singh", "FSJS", 1, 1234, true];
// Push Method pushing element inside array in last
myArray.push("Anurag", "Sir");
console.log(myArray);
// Output
["Atul", "Singh", "FSJS", 1, 1234, true, 'Anurag', 'Sir']
2:- Slice Method arrayName.slice( )
Slice method we put two index values first index value for where to start cutting the element and the last index value for where to end slicing but here is the catch the last index value is not participating in slicing.
slice() Syntax:
The syntax of the slice()
method is:
array.slice(start index, end index);
// Slice Method
let sliceArray = ["Atul", "Singh", "FSJS", 1, 1234, true];
//1st:- slicing the array from start to end
let arrStore = sliceArray.slice();
console.log(arrStore);
//2nd:- slicing from the second index
let arrStore1 = sliceArray.slice(1);
console.log(arrStore1);
//3rd:- slicing from second index to five index
let arrStore2 = sliceArray.slice(2, 5);
console.log(arrStore2);
//4th:- using also negative parameter for slicing
let arrStore3 = sliceArray.slice(1, -3);
console.log(arrStore3);
Output:
[ 'Atul', 'Singh', 'FSJS', 1, 1234, true ]
[ 'Singh', 'FSJS', 1, 1234, true ]
[ 'FSJS', 1, 1234 ]
[ 'Singh', 'FSJS' ]
- slice method is not modifying the original array it gives the new array and the old array is available as it is.
let arrStore2 = sliceArray.slice(2, 5);
console.log(arrStore2);
console.log(sliceArray);
Output:
[ 'FSJS', 1, 1234 ]
[ 'Atul', 'Singh', 'FSJS', 1, 1234, true ]
3:- Splice Method arrayName.splice( )
The splice method has three parameters first is the start index, the second parameter is how many remove elements and the third parameter is which element we want to update inside the existing array.
This splicing method is modified to the original array.
splice() Syntax:
The syntax of the splice()
method is:
array.splice(start index, how much element we want removed, value1, ... , value n);
- Example:
// 3rd:- Splice Method
let languages = ["JavaScript", "Python", "Java", "Lua"];
// adding elements without deleting existing elements
let removed = languages.splice(1, 0, "C", "C++"); console.log(removed); //[]
console.log(languages);//[ 'JavaScript', 'C', 'C++', 'Python', 'Java', 'Lua']
// replacing "Java" & "Lua" with "JS" & "React"
let removed1 = languages.splice(4, 2, "JS", "React"); console.log(removed1);//[ 'Java', 'Lua']
console.log(languages);//[ 'JavaScript', 'C', 'C++', 'Python', 'JS', 'React']
// removes everything from start
let removed2 = languages.splice(1); console.log(removed2);//[ 'C', 'C++', 'Python', 'JS', 'React' ]
console.log(languages);//[ 'JavaScript' ]
// remove none & add 3 more element
let removed3 = languages.splice(1, -2, "Swift", "Scala", "Go"); console.log(removed3); // []
console.log(languages); // [ "JavaScript", "Swift", "Scala", "Go"]
// remove last element and add 3 more elements
let removed4 = languages.splice(-1, 1, "java", "css", "node"); console.log(removed4); //[ 'Go' ]
console.log(languages); //[ 'JavaScript', 'Swift', 'Scala', 'java', 'css', 'node']
4:- concat Method arrayName.concat( )
We use this method to concatenate multiple values inside choosing array. This method first creates an array and then concatenates the elements. This gives a new array.
let num1 = [1, 2, 3, 4];
let num2 = [5, 6, 7, 8];
let num3 = [9, 10, 11, 12];
//concatinate three array
let conCatThreeArr = num1.concat(num2, num3);
console.log(conCatThreeArr);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
//adding one value and array
let concatOneValueAndArray = num3.concat("111", num2);
console.log(concatOneValueAndArray);//[ 9, 10, 11, 12, '111', 5, 6, 7, 8]
5:- fill Method arrayName.fill( )
Fill method fill the value inside the array of all indexes. The fill method has three parameters (value, start Index, and end Index).
value
:- This value is used to fill the array index.start
:- This is the start index. default index is zero(0).end
:- This is the end index. default is Array. length.
fill() Syntax:
The syntax of the fill()
method is:
array.fill(value, start, end);
- Example:
//fill() Method
//fill every index by "atul"
let arr = [1, 2, 3, 4, 5];
arr.fill("atul");
console.log(arr);//[ 'atul', 'atul', 'atul', 'atul', 'atul' ]
// replacing element of array from index 1 to 3 by 'JavaScript'
arr.fill("JavaScript", 1, 3);
// printing the original array
console.log(arr);//[ 'atul', 'JavaScript', 'JavaScript', 'atul', 'atul' ]
//start from negative index value
arr.fill("AAAA", -1);
console.log(arr);//[ 'atul', 'JavaScript', 'JavaScript', 'atul', 'AAAA' ]
//both negative index value
arr.fill("AAAA", -4, 3);
console.log(arr);//[ 'atul', 'AAAA', 'AAAA', 'atul', 'AAAA' ]
6:- includes Method arrayName.includes( )
Includes method checks the value inside the array whether the value is present or not, if the value is present then the return output is true, if not present then the return output is false.
Includes method have two parameter(value to find, from index number):-
value to find
: inside the array, the value searches forfrom index
: The position in the array where to start the search by default index starts from zero.
includes() Syntax The syntax of the includes() method is:
arr.includes(valueToFind, fromIndex)
//includes() Method
// defining an array
let languages = ["JavaScript", "Java", "C"];
//checking the array is containig "Java" or not
console.log(languages.includes("Java")); //true
//checking the array is containig "C++" or not
console.log(languages.includes("C++")); //false
// second argument specifies position to start the search
console.log(languages.includes("Java", 2)); //false
console.log(languages.includes("Java", 1)); //true
console.log(languages.includes("Java", 0)); //true
// the search starts from third last element
console.log(languages.includes("Java", -1)); //false
console.log(languages.includes("Java", -2)); //true
//include method is case sensitive
console.log(languages.includes("java")); //false
console.log(languages.includes("Java")); //true
7:- indexOf Method arrayName.indexOf( )
The index of the method searches the value inside the array and if present the value it gives the element index no
and not present inside the array then the output gives -1
. When it's finding an element this will stop and not check inside the array forward.
indexOf() Syntax
The syntax of the indexOf() method is: arr.indexOf(search element, fromIndex)
indexOf method has two parameters:-
Search element
: this first parameter searches the element inside the arrayfromIndex
: where to start index for search. By default, it is 0.
//indexOf() Method
let languages = ["Java", "Python", "JavaScript", "C", "JavaScript"];
// get the index of the first occurrence of "JavaScript"
let index = languages.indexOf("JavaScript");
console.log(index); // 2
// index start from 1 to searching value
let index1 = languages.indexOf("JavaScript", 1);
console.log(index1); // 2
// index start from 3 to searching value
let index2 = languages.indexOf("JavaScript", 3);
console.log(index2); // 4
8:- isArray Method arrayName.isArray( )
Is the array method checking whether the inside pass value is an array or not, in the output it gives the boolean value(true or false)?
isArray() Syntax
The syntax of the isArray() method is: Array.isArray(array variable name)
Example:
// isArray() Method
let num = [1, 2, 3, 4]; console.log(Array.isArray(num)); // true
// passing an simple variable
let num1 = 2; console.log(Array.isArray(num1)); // false
// passing an empty array
console.log(Array.isArray([])); // true
// we created an array with element 5 and passed that value to isArray()
console.log(Array.isArray(new Array(5))); // true
//passing undefined value to isArray()
console.log(Array.isArray(undefined)); // false
9:- join Method arrayName.isArray( )
The join method joins every element inside the array and separates the separator. It returns the value into a string and not changing the original array. The join method has one parameter it's called seperater.
join() Syntax
The syntax of the join() method is: arr.join(separator)
Example:
// declare the array
let num = [1, 2, 3, 4, 5, 6]; console.log(typeof num);// object
console.log(num); console.log(num. join()); //1,2,3,4,5,6
console.log(num. join("")); //123456
console.log(num. join(" ")); //1 2 3 4 5 6
// let check the datatype of the join method
// join method converted output into string
let var1 = num. join(" | "); console.log(var1); //1 | 2 | 3 | 4 | 5 | 6 c
onsole.log(typeof var1); //string
10:- lastIndexOf Method arrayName.lastIndexOf( )
Its method searches the value from backwords inside the array. The last Index Of the method has two parameters the first parameter is which values to search and the second is from which index to backward search.
lastIndexOf() Syntax
The syntax of the lastIndexOf() method is: arr.lastIndexOf(sepretor)
Example:
//lastIndexOf Method
let arr = [1, 2, 3, 4, "atul", 5, 6, "atul", 7, 8, "atul"]; //start searches the value from the last index because last index of start searches from last indexes
console.log(arr.lastIndexOf("atul")); // 10
//lastIndexOf() with two Parameters
// second argument specifies the starting index
// from where the method searches the element backward
console.log(arr.lastIndexOf("atul", 8)); // 7
// lastIndexOf() with Negative Parameter
// start the searches from last
console.log(arr.lastIndexOf("atul", -5)); //4
11:- map Method arrayName.map( )
The map method iterate over array elements only once and this method create a new array to store returned value. Inside the map, the method has two parameters one is the callback function and another one is thisArg.
callback function called every array element and operation and create a new array and stored the return value.
thisArg (optional) - Value to use as this when executing callback. By default, it is undefined.
map() Syntax The syntax of the map() method is:
arr.map(callback(currentValue), thisArg)
Example:
let num = [1, 4, 9, 16, 25];
let mapSqrt = num.map(Math.sqrt);
console.log(mapSqrt);
//this map method not modifing original array
console.log(num);
12:- pop Method arrayName.pop( )
The pop method removes the element from the last inside the array and returns the value, if the array is empty then return undefined
, this method modified the original array. The pop method does not have any parameters.
pop() Syntax The syntax of the pop() method is:
arr.pop()
Example: ```
// pop() Method let num = [1, 4, 9, 16, 25]; let pop method = num.pop(); //remove the last element inside array console.log(popMethod); // this method modifying the original array console.log(num); ```
13:- reverse Method arrayName.reverse( )
reverse method reverse all element inside the array and this method modifies the original array. The reverse() method does not take any parameters.
reverse() Syntax The syntax of the reverse() method is:
arr.reverse()
Example:
//reverse Method
let num = [1, 4, 9, 16, 25];
// reverse the element
console.log(num.reverse());
// modifing the original array
console.log(num);
14:- shift Method arrayName.shift( )
The shift method removes elements from the first position inside the array and this will change all element positions and modify the original array. The shift() method does not accept any arguments. Returns undefined if the array is empty.
shift() Syntax The syntax of the shift() method is:
arr.shift()
Example: ```
//shift() method let num = [1, 4, 9, 16, 25]; //shift element from the first position in the array and this will change all index position console.log(num.shift()); // 1 //modifying the original array console.log(num); //[ 4, 9, 16, 25 ] ```
15:- unshift Method arrayName.unshift( )
This method adds one are more elements inside from the array's first position so it will change every element's position. This method gives the length of the array and its modifying the original array.
unshift() Syntax The syntax of the unshift() method is:
arr.unshift()
Example: ```
let num = [1, 4, 9, 16, 25]; // this method gives the array length console.log(num.unshift(111, 222, 333, 444));//9 // change the original array console.log(num);// [111, 222, 333, 444, 1, 4, 9, 16, 25] ```
16:- sort Method arrayName.sort( )
The sort method is a sorted array element in ascending or descending order.
Every array element is first converted in the string before being sorted.
**and then this string value to compared using their UTF-16 code point value. **
The sorting is done in ascending order.
The
undefined
elements are sorted to the end of the array.This sort of method changed the original array and not made any copy of the array.
sort() Syntax The syntax of the sort() method is:
arr.sort(compare function)
Example: when compare function is not passed
//sort() Method
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
// sort the city array in ascending order
let sortedArray = city.sort();
console.log(sortedArray); //[ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]
console.log(city); //[ 'Barcelona', 'California', 'Kathmandu', 'Paris' ]
let num = [21, 6, 98, 176, 3, 1];
console.log(num.sort()); //[ 1, 176, 21, 3, 6, 98 ]
console.log(num); //[ 1, 176, 21, 3, 6, 98 ]
Example-2:
when compare function is passed
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
let ascend = city.sort(function (a, b) { return a.length - b.length; }); console.log(ascend); //[ 'Paris', 'Barcelona', 'Kathmandu', 'California' ]
console.log(city); //[ 'Paris', 'Barcelona', 'Kathmandu', 'California' ]
Explanation: here
when
a.length - b.length < 0
is smaller than zero then the a comes before ba.length - b.length > 0
when a.length - b.length is greater than zero, the b comes before a.when those lengths are equal to zero
a.length - b.length == 0
then elements come as it is.
In this example, we sorted the value according to the length and in ascending order.
Example-3: Inside the array, we have a numbers element, we want this element urgest ascending and descending order
//ascending and descending order argest using function parameter let num = [45, 7, 8, 67, 0, 8, 4, 343, 21];
let numAsc = num.sort(function name(a, b) { return a - b; }); //ascending order
console.log(numAsc); //[ 0, 4, 7, 8, 8, 21, 45, 67, 343]
//a-b<0(0-2 <0) then a comes before to b
//change original array
console.log(num); //[ 0, 4, 7, 8, 8, 21, 45, 67, 343]
let numAsc1 = num.sort(function name(a, b) { return b - a; }); //descending order
console.log(numAsc);//[343, 67, 45, 21, 8, 8, 7, 4, 0]
//a-b>0(343-67 >0) then b comes before to a
//change original array
console.log(num);//[343, 67, 45, 21, 8, 8, 7, 4, 0]
17:- split Method arrayName.split( )
The split method converts the variable element into the array and this method split the string into a single character and converts it into an array.
split() Syntax
arr.split();
Example
//split() Method
// converting into the array
let name = "Atul";
console.log(name.split());//[ 'Atul' ]
console.log(name.split(""));//[ 'A', 't', 'u', 'l' ]
18:- for of Method
For of method simply iterate over the array one by one, that's all.
Example
// for of Method
let upperName = ["atul", "singh"];
let pus = [];
for (const iterator of upperName) {
pus.push(iterator.toUpperCase());
}
console.log(pus); //[ 'ATUL', 'SINGH' ]
19:- break and continue
- break simply means to get out of the flow.
Example
for (let i = 0; i < 10; i++) {
if (i == 3) {
// console.log(i);
break; // simply break out of the block
}
console.log(i);
}
continue Simply continue means to skip at that point where will check the condition and continue to looping.
Example
for (let i = 0; i < 6; i++) {
if (i == 3) {
// console.log(i);
continue; // skip
}
console.log(i);
}