Array and methods

Empty array

let arr=[];

Array with elements

let arr=[10, 20, 30];

Access whole array

console.log(arr)

Access single element from an array

arr[0]

Length of array

arr.length

for loop in array

for(let i=0; i< arr.length; i++){
console.log(arr[i]);
}

for-in loop in array

for (let i in arr){
console.log(arr[i]);
}

for-of loop in array

for(let item of arr){
console.log(item);
}

Array methods

Method Description Example
arr.push(item) Add item at the end  
arr.pop() Remove item from end  
arr.shift() Remove item from start  
arr.unshift() Add item at the start  
arr.slice(start_index, end_index) Return new array by copying all items from given start index to end  
arr.splice(from_index, no_of_item, new_item ) Remove number of item from given index and add new item to array  
arr.forEach(function(item, index, arr){ }) Run a function for the each item  
arr.concat(item, [arr_of_item]) Create new array by concating items   
arr.indexOf(item) Return index of given matched item, otherwise false  
arr.lastIndexOf(item) Return index of given matched item in backward direction, otherwise false  
arr.includes(item) Return true if given item exists otherwise false  
arr.find(item) Return the item that passes the test.  
arr.findIndex(item) Return index of item otherwise false  
arr.filter(function(item, index, arr){ }) Return filtered items array from an array  
arr.map(function(item, index, arr){ }) Run a function for each item and it is widely used function and it can transform an item and return a new array.  
arr.sort() Sort an array  
arr.reverse() Reverse an array  
arr.join() Create string of array items  
arr.reduce(function(accumulator, item, index, array){ }, initial_value); Used to create a single resultant based on an array.  
© 2016 - 2022, All Rights are Reserved.