What is Array?
To store multiple values array is used. It allows storing duplicate elements and different datatypes. The array is changeable. An array can be empty also. Each element in an array has an index. This index starts from 0. The following diagram shows the array with its index.
Creating Array
The array is defined as follows
//Empty Array
const arr1= Array();
//or
const arr=[]; //This is recommended
const numbers=[1,2,3,4,0.5,68];
const tech=["node","angular","react","CSS"];
//Array can have different data types
const customer=[
"akshay",
30,
0.25,
true,
{
'country':india,
'city':india
}
]
We use const here as it will not allow using that variable name again.
Creating an Array using the Split method
let js = 'JavaScript'
const jsarray= js.split('')
console.log(jsarray); // ['J', 'a', 'v', 'a','S', 'c', 'r', 'i','p', 't']
let txt = 'JavaScript is best programming language'
const txtarray= txt.split(' ');
console.log(txtarray); //[ 'JavaScript', 'is', 'best', 'programming', 'language' ]
Accessing Array Element
By default, the array assigns an index starting from 0 to elements. We can use those indexes to access the elements.
//Access elements
const numarray=[10,12,56,14,8,7];
console.log(numarray[0]);//10
console.log(numarray[2]);//56
console.log(numarray[4]);//8
Modifying array element
We can use the index to change the value of any element
const numarray=[10,12,56,14,8,7];
numarray[0]="modified";
console.log(numarray); //[ 'modified', 12, 56, 14, 8, 7 ]
Array Methods
As an array is mutable so there are different methods available for manipulating an array.
Length
It will give the no of elements in the array.
const numarray=[10,12,56,14,8,7];
console.log(numarray.length); // 6
Push()
add one or more elements to the end of an array
const strarr=["items1","item2","item3"];
strarr.push("new Item");
console.log(strarr);//[ 'items1', 'item2', 'item3', 'new Item' ]
strarr.push("item5",6);
console.log(strarr); //[ 'items1', 'item2', 'item3', 'new Item', 'item5', 6 ]
Unshift()
add one or more elements to the beginning of an array.
const strarr=["items1","item2","item3"];
strarr.unshift("at start");
console.log(strarr);//[ 'at start', 'items1', 'item2', 'item3' ]
Pop()
remove the last element from the array
const strarr=["items1","item2","item3"];
let lastelement=strarr.pop();
console.log(lastelement);//item3
console.log(strarr);//[ 'items1', 'item2' ]
Shift()
remove the first element from an array.
const strarr=["items1","item2","item3"];
let element=strarr.shift();
console.log(element);//items1
console.log(strarr);//[ 'item2', 'item3' ]
Splice()
manipulate elements in an array such as deleting, inserting, and replacing elements
Deleting element-: splice(position, num):- This will delete several items specified by the num argument, starting from a position specified by the position argument. This method changes the original array and returns deleted elements array
const runs=[32,57,12,48,81,99]; let deleteelement= runs.splice(1,2); console.log(deleteelement);//[ 57, 12 ] console.log(runs);//[ 32, 48, 81, 99 ]
Inserting element: splice(position,0,new-elements):- The syntax is as follows
position:- the new element will be inserted from this position
0- zero for inserting the operation
new-elements- elements to be inserted
const run=[0,1,2,3,4,5,6]; run.splice(2,0,99,99,99); console.log(run);//[0, 1, 99, 99, 99,2, 3, 4, 5, 6] //elemnts added from position 2
Replacing elements: splice(position,delete-count,new-element)
position: starting position to delete elements and insert element
delete-count: Number of elements to be deleted
new-element: Add a new element
const run=[0,1,2,3,4,5,6]; run.splice(1,2,99,99,99); console.log(run); //[ 0, 99, 99, 99,3, 4, 5, 6] const run1=[0,1,2,3,4,5,6] run1.splice(3,1,88,88,"new-elements"); console.log(run1);// [ 0, 1, 2, 88, 88, 'new-elements', 4, 5, 6 ]
Slice()
copy elements of an array. slice(start, end). It will copy elements from position start to end-1.
const runs=[0,1,2,3,4,5,6]
let copyarray= runs.slice(0,3);
console.log(copyarray);//[ 0, 1, 2 ]
//clone array
let clonearray=runs.slice();
console.log(clonearray);//[0, 1, 2, 3,4, 5, 6]
IndexOf()
To locate an element in an array. The syntax is indexOf(search-element,from-index). This method will return the index of the element or -1 if it does not exist. If there are multiple elements in the array then it will return the first element index. If the from-index argument is given then, it will start the search from that index.
const score=[10,12,15,20,10,10,35,40];
console.log(score.indexOf(12)); //1 => 12 present at position 1
console.log(score.indexOf(99));// -1 => not exist
console.log(score.indexOf(10));// 0 => first occourance of that element
//using from index argument
console.log(score.indexOf(10,1));// 4 => it will start search from index 1
LastindexOf()
when there are duplicate elements present in the array this method will give an index of the last occurrence.
const numbers = [1, 2, 3, 4, 5, 3, 2]
console.log(numbers.lastIndexOf(2)) // 6 => last occurance of 2
console.log(numbers.lastIndexOf(0)) // -1 => not exist
console.log(numbers.lastIndexOf(4)) // 3 => index of 4
Includes()
check if an element is in an array. includes(element,from-index). It will return true if the element is present in the array. If the from-index argument is given then, it will start the search from that index.
const numbers=[12,15,18,95,58,42,63];
console.log(numbers.includes(12));// true =>exist in array
console.log(numbers.includes(99));// false => not exist
console.log(numbers.includes(12,1));
// false it will start search from index 1
ToString()
It converts the array to a string. By default, it will join elements by a comma.
const str=[1,2,3];
console.log(str.toString());// 1,2,3
const str1=["a","p","j"];
console.log(str1.toString());// a,p,j
Join()
It converts the array to a string. But we can pass parameters by which elements will be joined.
const str=[1,2,3];
console.log(str.join(' '));// join by space 1 2 3
const str1=["a","p","j"];
console.log(str1.join('$'));//join by doller a$p$j
Concat()
It creates a new array by merging two or more arrays. The original array remains the same.
const odds = [1,3,5];
const evens = [2,4,6];
// merge odds and evens array
const combined = odds.concat(evens);//
console.log(combined);// new array=>[ 1, 3, 5, 2, 4, 6 ]
console.log(odds);//[ 1, 3, 5 ]
console.log(evens);//[ 2, 4, 6 ]
Map()
This method transforms array elements according to a given function and returns a new array. The arrow function is used here.
const circles = [3, 5, 9];
// let areas = circles.map(circleArea);
let areas= circles.map((r)=> 3*r*r);
console.log(areas);//[ 27, 75, 243 ]
Filter()
This method will filter the elements of an array according to a given function.It will create an array with elements that satisfy the given condition.
let num = [10,12,-5,-9,5,-9,52,-8];
///array of positive numbers
let positiveNumbers = num.filter(n=> n>0);
console.log(positiveNumbers);//[ 10, 12, 5, 52 ]
Every()
It returns true if every element in the array passes the specified condition.
let numbers = [1, 3, 5];
console.log(numbers.every(n => n<6));//true
console.log(numbers.every(n => n<1));//false
Some()
It returns true if at least one element in the array passes the specified condition.
let numbers = [1, 3, 5];
console.log(numbers.some(n => n<2));//false
Sort()
This method sorts the original array. This method considers each element in the array as a string and then performs a sort operation. It works fine for an array of strings but for an array of numbers we pass compare function to sort it properly.
const stringArray=['z','w','a','d'];
stringArray.sort();
console.log(stringArray);//[ 'a', 'd', 'w', 'z' ]
const numArray=[10,5,12,84,25];
//if we use only sort
numArray.sort();
console.log(numArray);// [ 10, 12, 25, 5, 84 ]
//For number array we use compare funtion
numArray.sort((a,b)=>a-b);
console.log(numArray);// 5, 10, 12, 25, 84 ]
Reverse()
reverse the order of the array
const numbers = [1, 2, 3, 4, 5]
numbers.reverse() // -> reverse array order
console.log(numbers) // [5, 4, 3, 2, 1]
Summary
The following table gives a summary of all array methods
Thanks for Reading!!!!!
Name | Use | Comment |
array.length | gives the length | |
array.push() | add an element at the end | original array modified |
array.unshift() | add an element at the start | original array modified |
array.pop() | remove the last element | original array modified |
array.shift() | removes the first element | original array modified |
array.splice() | delete, insert, replace | original array modified |
array.slice() | copy elements from an array | |
array.indexOf() | find an index of the element | |
array.lastindexOf() | index of the last occurrence | |
array.includes() | check element is present or not | |
array.toString() | convert to string using a comma | |
array.join() | convert to sting using the argument | |
array.concat() | merge multiples array | |
array.map() | apply condition on every element | |
array.filter() | filter elements with condition | |
array.every() | check every element | |
array.some() | check elements | |
array.sort() | sort the element | |
array.reverse() | reverse order |