Array Method in Javascript: An introduction for beginners
Here we will cover about Array & Array Methods of JS in detail.
Introduction
What is Array?
In simple terms, an Array is an object which is a non-primitive datatypes category, and it means that we can assign it a group of values at once. It is enclosed by square brackets. In other words, Arrays in JavaScript are used to store multiple elements inside a single variable reference. These multiple elements can be of similar data types or different data types. Let us understand the syntax and how we create it.
let EmptyArr=[]; // Empty Array Using Literal Array
//Here our array contains multiple elements of same data type i.e String
let langs = [ "Java", "python", "Ruby", "javascript", "kotlin", "PHP"];
// Here our array contains multiple elements of different data types even we can store an another array inside an array
let info=["yash",12235, false,{Phone: 5325234, email: "xyz123@gmail.com"}]
Array Declaration
There are two ways by which we can declare a variable such as:
Array Literal.
New keyword.
Method-1 --> Preferred // Array Literal let arr1 = [ "value1", "value2", "value3"...... ]; Method-2 --> Not Preferred // New Keyword let arr2 = new Array( "value1", "value2", "value3"...... );
Method 1 is preferred over method 2 Because Of So in Method 2, we can't get an array that contains only one element. That's why we do not prefer to use this method.
//Initializing while Declaraing
//Method 1
let num = [5 , 10];
console.log(num1); // [5,10]
//Method 2
let num1 = new Array(2);
console.log(num2); // [undefined, undefined]
Role of Array Methods.
Array methods are work like a functions in JavaScript that we can apply to our arrays.
Each method has a specific function that performs a change or calculation to our array.
These methods save our time in writing the whole function for different-different requirements and also helps in avoiding complexities.
Every Method have a own functionally according to array task work its a predefined function by Js.
Array Index
In programming, the index starts from 0, not from 1. With the help of the index, we can target individual elements inside an array. You can say that index means the position of the particular element inside the array.
let arr1 = ["Yash", "Sachin", "Savinder", "Vipin", "Jaspreet"]
// index 0 1 2 3 4
// We can also conclude that...
// Index of last element of an array = array.length-1
If we use a typeof operator on the array we find that array is an object type i.e. non-primitive data type and non-primitive data types (objects, Arrays) are mutable in JavaScript and the primitive data types ( Number, String, Boolean, etc.) are immutable. What is Mutability?
Mutability means that a Mutable value or data can be modified or changed without creating a new value.
let's understand it with an example.
// We have this array car which contains 4 elements
let car = ["BMW", "Marutisuzki", "KIA", "TATA"];
console.log(car);
// ["BMW", "Marutisuzki", "KIA", "TATA"]
//Now mutability means that we can change or modifiy content of this array
car[1] = "SUZUKI";
console.log(car);
// ["BMW", "SUZUKI", "KIA", "TATA"]
//Here you can see that 2nd element (at position index 1 ) has changed in the original array.But we can't do this with primitive data types.
let str = "HELLO";
console.log(str[0]) // "H"
str[0] = "Y";
console.log(str[0]) //"H"
console.log(str) //"HELLO"
//Here you can see that first character of string str has not changed Because String is immutable
One more thing does not confuse mutability with an assignment to a variable. They both are completely different things.
/////
let str = "BOlNAHALKE";
str = "NAHALKE";
//See here we are not changing or modifying the value or string "BOLNAHLAKE". We are creating a new value "Ravinder" which will now be inside container (Variable) str. It is not mutability because a new value "NAHALKE" is created. We haven't modified anything in the "BOlNAHALKE".
Convert Array to String
Array.toString()
It will convert the array into a string. It will return the converted string. The original array won't be modified.
let arr1 = [1,2,3,4,5,6,7,8,9,10];
console.log(arr1) // [1,2,3,4,5,6,7,8,9,10]
let str1 = arr1.toString();
console.log(str1) // 12345678910 (it's a string not an array)
console.log(typeof str1) // String
console.log(arr1); // [1,2,3,4,5,6,7,8,9,10] (original arr is not modified)
Array.join()
It will join the items of the array and returns a string. It won't update the original array.
let arr = [1,2,3,4,5];
console.log(arr) // [1,2,3,4,5]
let str = arr.join("-")
console.log(str); // 1-2-3-4-5 it's a string not an array)
console.log(arr) // [1,2,3,4,5] (original arr is not modified)
Array.concat()
It is used to join arrays to a given array. It will return a new array and won't modify the original array.
let arr = [1,2,3,4,5,6,7];
console.log(arr) // [1,2,3,4,5,6,7]
let arr2 = [8,9,10,11,12,13]
let arr3 = [14,15,16,17,18,19,20]
let arr4 = arr.concat(arr2,arr3);
console.log(arr4) // [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
console.log(arr) //[1,2,3,4,5,6,7] (original arr is not modified)
Array.reverse()
It will reverse the positions of the elements present in an array. It modifies the original array.
let arr = [1,2,3,4,5];
console.log(arr) // [1,2,3,4,5]
arr.reverse();
console.log(arr) // [5,4,3,2,1]
Array.slice()
It slices out a piece from an array. It does not modify the original array but returns a new array.
let arr = [1,2,3,4,5,6,7];
console.log(arr) // [1,2,3,4,5,6,7]
console.log(arr.slice(2)) // [3,4,5,6,7] from index 2 to last element of array.
console.log(arr.slice(1,6))// [2,3,4,5,6] from index 1 to 5 (6-1)
console.log(arr) //[1,2,3,4,5,6,7]
Array.splice()
Splice() can be used to add items in an array at a given particular position. It can also delete elements. It returns the deleted items and modifies the original array.
let arr = [1,2,3,4,5,6,7];
console.log(arr) // [1,2,3,4,5,6,7]
console.log(arr.splice(2,3,"Ram","Krishna","Kalki")) //[3,4,5], return deleted items
console.log(arr) //[ 1, 2, 'Ram', 'Krishna', 'Kalki', 6, 7 ] modifies original array
Array.sort()
If we are using the sort() method on an array. It will first convert each element of the array into a string then comparison happens based on their UTF-16 code and the order of comparison is ascending.
let tv = ["Naruto", "Spiderman", "drangon" ,"pokemon", "Batman", "Superman"]
tv.sort();
console.log(tv)
Output Is
['Batman', 'Naruto', 'Spiderman', 'Superman', 'drangon','pokemon']
So in UTF-16 code ascending order "Spiderman" comes before "dragon". Wait, What?
Wait, don't overreact, Let me explain! How UTF-16 code comparison happens. So what sort method will do it will first convert all elements of an array into a string (We already had array elements as string). Now it will convert each string into UTF-16 code, where each alphabet has a unique numerical code. But comparison happens only based on the first character's Unicode. But if the first character's Unicode is the same then the comparison goes to the second character's Unicode value and so on...
let tv= ["Naruto", "Spiderman", "drangon" ,"pokemon", "Batman", "Superman"]
for(let code of tv){
console.log(`The unicode value of ${code[0]} is ${code.charCodeAt(0)}`)
}
//////////////////////////////////////////////////////////////////////
/**********************Output**********************/
The unicode value of N is 78
The unicode value of S is 83
The unicode value of d is 100
The unicode value of p is 112
The unicode value of B is 66
The unicode value of S is 83
So if you want to arrange words into alphabetical order using sort() make sure that their first character is either in lowercase or uppercase not like some are in uppercase & some are in lowercase. Then sort method will work.
Now, How can we arrange them in Numerical Ascending and Numerical Descending order?
let num = [5,88,95,6,15,36,17,56];
num.sort();
console.log(num) // [15, 17, 36, 5,56, 6, 88, 95]
//We know that all array elements first converted to string
["5", "88", "95" ,"6", "15", "36", "17", "36"]
Now we know how we get this output. This [15, 17, 36, 5,56, 6, 88, 95] is in ascending order but based on Unicode values.
- For that JS allows us to pass a compare function as an argument to the sort method and based on that compare function sorting happens.
//Ascending order
let num = [5,88,95,6,15,36,17,56];
num.sort((a,b)=>{
return a-b;
});
console.log(num) // [5, 6, 15, 17, 36, 56, 88, 95]
/////////////////////////////////////////////////
//Descending order
let num = [5,88,95,6,15,36,17,56];
num.sort((a,b)=>{
return b-a;
});
console.log(num) //[95, 88, 56, 36, 17, 15, 6, 5]
Delete
Delete is not an array method but it is an operator which is used to delete array elements. The delete operator modifies the original array but won't change its original length.
let arr = [1,2,3,4,5,6,7]
delete arr[3];
console.log(arr) // [ 1, 2, 3, <empty item>, 5, 6, 7 ]
Array.fill()
Fill Method is it replaces elements of an array with the given value, from index 0 to end index (array. length). It also modifies the original array and also returns the modified array.
1 Example
let arr = [1,2,3,4,5,6,7]
console.log(arr.fill("FSJS")) //['FSJS','FSJS','FSJS','FSJS','FSJS','FSJS','FSJS']
console.log(arr)
//['FSJS','FSJS','FSJS','FSJS','FSJS','FSJS','FSJS']
2 Example
let arr = [1,2,3,4,5,6,7]
console.log(arr.fill("FSJS")) //['FSJS','FSJS','FSJS','FSJS','FSJS','FSJS','FSJS']
console.log(arr)
//['FSJS','FSJS','FSJS','FSJS','FSJS','FSJS','FSJS']
3 Example
let arr = [1,2,3,4,5,6,7];
//from index 1 till index 4 (5-1)
console.log(arr.fill("FSJS",1,5));
//[1,'FSJS','FSJS', 'FSJS','FSJS', 6,7]
IndexOf()
It returns the index of the first occurrence of that element. It returns -1 if the element is not present in the array.
let names = ["garry", "raju", "bolu", "chutki","garry"];
console.log(names.indexOf("garry")); // 0 i.e index of first occurrence
lastIndexOf()
It returns the index of the last occurrence of that element. It returns -1 if the element is not present in the array.
let names = ["garry", "raju", "bolu", "chutki","garry"];
console.log(names.lastIndexOf("garry")); //4, index of last occurrence
split()
This is a string method. It will take a pattern as an argument and based on that pattern it will convert the string into a substring and put these substrings inside the array and returns that array.
let firstName = "Yaash";
let arr1 = firstName.split("");
console.log(arr1); // ['Y', 'a', 'a','s', 'h']
let text = "This FSJS 2.0 Bootcamp by Hitesh Sir & iNeuron is Awesome";
let arr2 = text.split(" ");
console.log(arr2)
// ['This','FSJS','2.0','Bootcamp','by','Hitesh','Sir', '&','iNeuron', 'is','Awesome']
Array.isArray()
It tells whether the passed value is an array or not. It returns a boolean value that is either true or false.
let firstName = "Yash";
console.log(Array.isArray(firstName)) //false
if(Array.isArray(firstName)){
console.log(`${firstName} is an array`)
}else{
console.log(`${firstName} is not an array`)
}
// Yash is an array
Array.includes()
It takes two arguments first is the element that needs to search in the array & second is the index from where till the last index it will search that element in the array. It returns a boolean-type value if the element is present the return is true, else false. If the second argument i.e. indexFrom is missing then it will search the whole array.
let languages = [ "python", "Ruby", "javascript", "kotlin", "PHP", "java" ];
// Search the whole array
console.log(languages.includes("javascript")) // true
// search from index 1 till last index
console.log(languages.includes("javascript",1)); // true
// search from index 2 till last index
console.log(languages.includes("javascript",2)); //true
// search from index 3 till last index
console.log(languages.includes("javascript",3)); //false
// search from index 4 till last index
console.log(languages.includes("javascript",4)); //false
Array.from()
Array. from() converts an array-like object (which is iterable and uses index & length properties e.g. Map, Set, HTML Collection) to an array. It returns a new array. If the object is not iterable then also it converts into an array. The first argument is an array-like object & second is a callback.
let num = "123456789"
// Although here num is string but is also be any array like iterable object.
let arr = Array.from(num,(element)=>{
return element*element;
})
console.log(num) //123456789
console.log(arr) // [1, 4, 9, 16, 25, 36, 49, 64, 81]
Array.map()
It creates a new array. It takes a callback function as an argument and the function to execute for each element in the array. Its return value is added as a single element in the new array.
let arr = [1,2,3,4,5]
let arr2 = arr.map(element=>{
return element*element*element;
})
console.log(arr2) // [ 1, 8, 27, 64, 125 ]
for of loop
Well instead of a traditional for loop we can use for-of-loop on an array for simplicity. The for-of-loop iterate on each array element.
let arr = [1,2,3,4,5]
for(let item of arr){
console.log(`The square of ${item} is ${item*item}`)
}
//The square of 1 is 1
//The square of 2 is 4
//The square of 3 is 9
//The square of 4 is 16
//The square of 5 is 25
Adding & Removing elements in an array
Array. pop()
It will remove the last element of the array and it will also modify the original array.
let arr = [1,2,3,4,5,6,7]
console.log(arr) // [1,2,3,4,5,6,7]
//array.pop() will remove the last element of an array & modifies the original array. It will return the removed element.
arr.pop();
console.log(arr) // [1,2,3,4,5,6]
Array. push(item)
It will add the given item at the last index of an array. It also modifies the original array.
let arr = [1,2,3,4,5,6,7]
console.log(arr) // [1,2,3,4,5,6,7]
//It will add the given item at the last index of an array. It also modifies the original array.
arr.push(8);
console.log(arr) // [1,2,3,4,5,6,7,8]
Array. shift()
It will remove the first element of the array and it will also modify the original array.
let arr = [1,2,3,4,5,6,7]
console.log(arr) // [1,2,3,4,5,6,7]
arr.shift();
console.log(arr) // [2,3,4,5,6,7]
Array. unshift(item)
It will add the given item at the start of an array. It also modifies the original array.
let arr = [1,2,3,4,5,6,7]
console.log(arr) // [1,2,3,4,5,6,7]
arr.unshift(0);
console.log(arr) // [0,1,2,3,4,5,6,7]
Thank you for giving your precious time in reading it.
If you find it useful Please do let me know. Your kind reviews are Welcomed.
Happy Learning :)