Javascript Array
By Saket Bhatnagar••Beginner to Intermediate
Array
- 1Array is object in javascript.
- 2It is non-primitive type of literal.
- 3It is a block of memory which is used to store multiple type of value (any type of literal) in same memory block.
- 4Array size is dynamic (size is not fixed like JAVA) , it means we can store 'N' number of elements and JS engine will handle memory usage automatically.
- 5Values stored inside array are refered as array elements.
- 6Array elements are arranged in a sequence that is represented by integer number called as index. Array index starts from zero to array size - 1 (suppose array has 5 elements it's first index will be - 0 and last index will be 4).
- 7We can access the array element with the help of array object reference , square brackets and index ( array_object_ref[index] ).
- 8If we try to access the index that it greater than the array length we will get undefined.
- 9Array elements should be separated by comma(,)
Ways to create array
- 1
By using square brackets [] and literals.
1let arr = [];2// empty array34let arr = [10,20,30];5// array with literals - 2
By using new keyword and Array() constructor.
1let arr = new Array();2//empty array34let arr = new Array(10,20,30)5//array with literals -> [10,20,30]NOTE : Here , 'arr' is a variable which holds the reference of array object. To access array element at index -> 1 Syntax : array_object_ref[index]Example : console.log(arr[1]); // 20
Array methods
push(value) method
- 1It is used to insert element at last of array.
- 2It returns the length of array.
- 3
Example:
1let arr=[10,20,30,40,50];2arr.push(100);3output: [10,20,30,40,50,100]
pop() method
- 1It is used to delete element from last index of array.
- 2It returns deleted element.
- 3
Example:
1let arr=[10,20,30,40,50];2arr.pop();3output: [10,20,30,40]
unshift(value)
- 1It is used to insert element at first index of array.
- 2It returns array length
- 3
Example:
1let arr=[10,20,30,40,50];2arr.unshift(200);3output: [200,10,20,30,40,50]
shift() method
- 1It is used to delete element from first index of array.
- 2It returns deleted element.
- 3
Example:
1let arr=[10,20,30,40,50];2arr.shift();3output: [20,30,40,50]
splice() method
- 1It is used to perform insertion , deletion and updation in array.
- 2It will modify the original array.
- 3It returns array of deleted elements.
- 4
Example:
1arr_ref.splice(a,b,c)2a - starting index3b - number of elements to be deleted4c - elements to be inserted - 5
Example : Delete three elements from index 1.
1let arr=[10,20,30,40,50];2arr.splice(1,3); // deleted: [20,30,40]3console.log(arr);45Output : [10,50] - 6
Example : Update value at index 3 to 500.
1let arr=[10,20,30,40,50];2arr.splice(3,1,500);3console.log(arr);45Output : [10,20,30,500,50] - 7
Example : Insert 100,200,and 300 from index 2.
1let arr=[10,20,30,40,50];2arr.splice(2,0,100,200,300);3console.log(arr);45Output : [10,20,100,200,300,30,40,50]
slice() method
- 1It is used to copy array elements.
- 2It will not modify the original array
- 3It returns array of copied elements.
- 4
Syntax :
1arr.slice(a,b);2a - starting index3b - last index45Here, last index is excluded -> last index -1 - 5
Example : Copy array from index 0 to 2.
1let arr=[10,20,30,40,50];2let copy_elements = arr.slice(0,3);3console.log(copy_elements);45Output: [10,20,30]
indexOf() methods
- 1It used to get the index of array element.
- 2If element is available -> it returns element's index.
- 3If element is not available -> it returns -1.
- 4
Syntax :
1arr.indexOf(a,b)2a - value to be searched3b - search starting index45If we does not pass last argument , it will 0 by default.6 - 5
Example : Check given array has element 30 or not and search from index 0 and 3 , if present print index.
1let arr=[10,20,30,40,50];2console.log(arr.indexOf(30)); // 23console.log(arr.indexOf(30,3)); // -14
includes() method
- 1It is used to check element is available or not.
- 2If element is available -> returns true.
- 3If element is not available -> returns false.
- 4
Syntax :
1arr_ref.includes(a,b);2a - value to be searched3b - search starting index45If we does not pass last argument , it will 0 by default. - 5
Example : Check given array has element 30 or not and search from index 0 and 3 , if present print true.
1let arr=[10,20,30,40,50];2console.log(arr.includes(30)); // true3console.log(arr.includes(30,3)); // false4
reverse() method
- 1It is used to reverse the array.
- 2It will modify the original array.
- 3
Example:
1let arr=[10,20,30,40,50];2console.log(arr.reverse());34Output: [50,40,30,20,10]
sort(callback) method
- 1It will modify the original array
- 2If callback returns -ve value -> it will sort in ascending order
- 3If callback returns +ve value -> it will sort in decending order.
- 4If callback returns 0 value -> it will not sort.
- 5
Example : Sort array in ascending order.
1let arr = [100, 2000, 380, 940, 50, 0, 2];2console.log(arr.sort((a, b) => a - b));34Output: [ 0, 2, 50, 100, 380, 940, 2000 ] - 6
Example : Sort array in descending order.
1let arr = [100, 2000, 380, 940, 50, 0, 2];2console.log(arr.sort((a, b) => b - a));34Output: [ 2000, 940, 380, 100, 50, 2, 0 ]
foreach(callback)
- 1It is a higher order function.
- 2It is used to iterate over array elements and index.
- 3It doesnot return anything , so js engine implicitly returns undefined.
- 4
Syntax :
1arr_ref.foreach((value,index,array)=>{2 // statements3}) - 5
Example : Print Even numbers from given array.
1const arr = [1, 2, 3, 4, 5];2arr.forEach((val)=> {3 if(val % 2 === 0)4 {5 console.log(val+" "+"is even number;");6 }7});
map(callback)
- 1It is a higher order function.
- 2It is used to iterate over array.
- 3It will not modify original array.
- 4It returns a new array.
- 5The value returned by callback function will be inserted in new array , if it doesnot return anything 'undefined' will be stored.
- 6
Syntax :
1arr_ref.map((value,index,array)=>{2 // statements3}) - 7
Example: Create new array where each element of given array is multiple of 8.
1let arr=[10,20,30,40,50];2let new_arr = arr.map(value => value * 8 );3console.log(new_arr);45Output: [80,160,240,320,400]
filter(callback)
- 1It is a higher order function.
- 2It is used to iterate over array.
- 3It will not modify original array.
- 4It returns a new array.
- 5Here, element will be inserted in new array only when callback function returns true.
- 6
Syntax :
1arr_ref.filter((value,index,array)=>{2 // statements3}) - 7
Example: Create new array where elements are greater than 40.
1let arr=[10,20,30,40,50,60,70];2let new_arr = arr.filter(value => {3 if(value > 30)4 return true;5});6console.log(new_arr);78Output: [40,50,60,70]
reduce(callback,initial_value)
- 1It is a higher order function.
- 2It is used to iterate and conclude result to a single value.
- 3It will not modify original array.
- 4It returns a single value.
- 5Here , single value is returned after complete iteration of array. Value is stored in a variable which is used to result , we refer it as accumulator.
- 6
Syntax :
1arr_ref.reduce((accumulator,value,index,array)=>{2 // statements3},initial_value_of_accumulator)If we does not pass initial value of accumulator first element of array will be stored automatically.
- 7
Example : Find the sum of all elements of array.
1let arr=[10,20,30,40,50,60,70];2let result = arr.reduce((acc,value) => {3 acc = acc + value;4 return acc;5},0);6console.log("Sum of all elements : ",result);78Output: Sum of all elements : 2809
Array.isArray(literal)
- 1It is used to check given literal is array or not.
- 2If it is array -> it will return true.
- 3if it is not array -> it will return false.
- 5
Example: Check given literal is array or not.
1console.log(Array.isArray({})); //false2console.log(Array.isArray(10)); //false3console.log(Array.isArray([10,20,30])); //true
Array.from(literal)
- 1It is used to convert iterable literals (like object or string) to array.
- 2If literal is iterable -> it returns new array of elements.
- 3If literal is not iterable -> it returns empty array.
- 4
Example : Convert string to Array.
1const str = "hello";2const arr = Array.from(str);3console.log(arr);45Output: ["h", "e", "l", "l", "o"]