Table of contents
- What is an array?
- Declaration Using Constructor
- Static Array Methods
- Instance properties
- Instance Methods
- Array.at()
- Array.concat
- Array.copyWithin()
- Array.entries()
- Array.every()
- Array.fill()
- Array.filter()
- Array.find() and Array.findLast()
- Array.findIndex() and Array.findLastIndex()
- Array.flat()
- Array.flatMap()
- Array.forEach()
- Array.includes()
- Array.indexOf() and Array.lastIndexOf()
- Array.join()
- Array.map()
- Array.pop()
- Array.push()
- Array.reduce()
- Array.reverse()
- Array.shift()
- Array.unshift()
- Array.slice()
- Array.some()
- Array.sort()
- Array.splice()
What is an array?
Well, In programming it is just a collection of some similar or non-similar data. In Javascript, there is no restriction on array type. For example
int arr[] = { 10, 20, 30, 40};
the above array contains only numbers and is in the syntax of C++ language, as you can see the type int
has been mentioned.
let arr = [ 'Cars', 4, true, ['this' ,'is' ,'subarray']]
However, In Javascript, we don't need the type declaration, which is a good or bad thing depending on the situation. The above example demonstrates the declaration of an array. In Programming arrays play a vital role. Javascript has provided us with multiple functions to make our life easier in development. In this Article we will be discussing the various aspects of the array functions in Javascript.
Declaration Using Constructor
We can declare array via above method called literal notation or constructor
const numbers = [1,2,3,4,5]
Another method to declare the array using the constructor
const numbers = new Array(1,2,3,4,5)
We can also declare array length like
const numbers = new Array(5)
Static Array Methods
Array.from()
We can use static array methods to create a new arrays from some data we have. The syntax is Array.from()
Array from a String:
const name = 'mango'
console.log(Array.from(name))
Array after performing some operation:
The Syntax is Array.from(array, function)
const arr = [1,2,3]
console.log(Array.from(arr, x => x*x))
Array.isArray()
This Array function checks if the given parameter is an array or not. It returns true
if it is an array otherwise it returns false
const arr = [1,2,3];
const name = 'mango';
console.log(Array.isArray(arr));
console.log(Array.isArray(name));
Array.of()
The Array.of()
method creates a new Array from the arguments given regardless of type.
console.log(Array.of('travel'));
console.log(Array.of(1,2,3));
Instance properties
Array.length
This is a widely used property that gives us the length of the array, array.length
const numbers = [1,2,3,4,5,6,7,'q','w','4',3]
console.log(numbers.length);
Instance Methods
Array.at()
This method returns array item at
a given index
, It also accepts negative integers as arguments and counts back from the last element.
Array.at()
, This is a fairly new method so it might not be available for you in your environment.
const numbers = [1,2,3,4,5,6,7,'q','w','4',3]
console.log(numbers.at(5));
console.log(numbers.at(-8));
Array.concat
This is a method which concatenates two different arrays into one array.
array1.concat(array2)
const numbers = [1,2,3,4,5,6,7]
const numbers2 = ['q','w','4',3]
console.log(numbers.concat(numbers2))
Array.copyWithin()
The copyWithin()
method copies part of an array to another location in the same array and returns it without modifying its length. It can take 3 arguments but atleast one argument must be present
array.copyWithin(target,start,end)
const numbers = [1,2,3,4,5,6,7,'q','w','4',3]
console.log(numbers.copyWithin(0,3,4))
console.log(numbers.copyWithin(0,3,7))
Array.entries()
This method gives us the index/value of the array elements. We can
const num = ['a','b','c','d']
for(const [index,element] of num.entries()){
console.log(index,element)
}
Array.every()
This method checks if all the elements of the given array satisfies the condition. It returns true if all elements meet the condition otherwise false. We have taken a simple even number example
const isEven = (value) => value%2===0
const arr1 = [2,4,6,8]
const arr2 = [2,4,6,7]
console.log(arr1.every(isEven))
console.log(arr2.every(isEven))
Array.fill()
This is a method used to change array elements to a static value, it modifies the original array. General syntax
fill(value,startIndex,endIndex)
Here start Index and end index are optional, without these all elements will be replaced by the value. Also just like the .at()
method we can use negative integers to start from the end of Array
console.log([1,2,3,5].fill(4));
console.log([1,2,3,5].fill(4,1))
console.log([1,2,3,5].fill(4,1,2))
console.log([1,2,3,5].fill(4,-3,-2))
console.log(Array(4).fill(4))
Array.filter()
This returns new array containing all the elements of the calling array for which the filter condition is true
. It takes a callback function to check the condition.
const num = [1,2,3,4,5,6,7,8,9]
console.log(num.filter(ele => ele%2!==0))
Array.find() and Array.findLast()
The find()
method returns the first element in array which satisfies the given condition. If no values found it returns undefined
The findLast()
method returns the last element in array which satisfies the given condition instead of the first like in find(). If no values found it also returns
undefined`
//example contains only find()
// findLast() also works same but returns last element.
const num = [1,2,3,4,5,6,7,8,9]
console.log(num.find(ele => ele>7))// check for number greater than 7
Array.findIndex() and Array.findLastIndex()
The findIndex()
method returns the index of the first element in the array which satisfies the given condition. If no elements are found, it returns -1.
The findLastIndex()
method returns the index of the last element in the array which satisfies the given condition. If no elements are found, it returns -1.
// example only contains of findIndex()
// findLastIndex() works the same but will return last element index.
const num = [1,2,3,4,5,8,6,7,9]
console.log(num.findIndex(ele => ele>7))//8 is at index 5
console.log(num.findIndex(ele => ele>10))// no element greater than 10
Array.flat()
This method creates a new array with all the sub-array elements added in order into it recursively up to the specified depth
const num = [1,2,3,4,[5,6,7],8,9]
console.log(num.flat())
const num2 = [1,2,3,4,[5,[[6]],7],8,9]
console.log(num2.flat(2))
Array.flatMap()
This method returns a new array which is formed according to the condition given in the callback function to each element of the array, and then flattens the result by one level.
const num = [1,2,3,4,[5,6,7],8,9]
console.log(num.flatMap((ele) => ele*2))
console.log(num.flatMap((ele) => ele))
Array.forEach()
This is a method for the array which works with each element and applies the function to each element.
const num = [1,2,3,4]
num.forEach(ele => console.log(ele*ele))
Array.includes()
This method checks for a certain value among the entries of the array and returns true
if value is found else false
const num = [1,2,3,4]
console.log(num.includes(4))
Array.indexOf() and Array.lastIndexOf()
These two method returns the first and last index of the given element much like Array.findIndex()
and Array.findLastIndex()
method we saw earlier but unlike previous method, indexOf()
allows us to decide which index to start the search from.
array.indexOf(searchElement)
array.indexOf(searchElement, fromIndex)
array.lastIndexOf(searchElement)
array.lastIndexOf(searchElement, fromIndex)
const num = [1,2,3,4,5,6,7,8,9,5,6,4,4,5,4]
console.log(num.indexOf(4,5))
console.log(num.lastIndexOf(4,num.length-2))
As you can see we started from the index 5
which holds the value 6
so we got the first 4
after 6
which was at the last index of 11
. And for the lastIndexOf()
we got num.length
which is 15
and we started with 13th
index and going reverse we got 4
at 12th index
Array.join()
This is a method used to join elements of array with a specific separated which is optional. The join()
method creates and returns a new String by concatenating all the elements in an array. By default the separator is commas. If array has only one item it will remain unaffected.
arr.join()
`arr.join('-')
const name = ['m','a','n','g','o']
console.log(name.join())
console.log(name.join('-'))
console.log(name.join('_'))
Array.map()
The map()
method is another of the popular method people use. It creates new array and populates it with the results of calling the function on every element in the array
const numbers = [1,2,3,4,5,6,7]
const squaredNum = numbers.map(ele => ele*ele)
console.log(squaredNum)
Array.pop()
The pop()
method removes the last element from an array and returns that element. This changes the original array's length
const numbers = [1,2,3,4,5,6,7]
console.log(`The Length before pop() is : ${numbers.length}`)
const popped = numbers.pop()
console.log(`The removed element : ${popped}`)
console.log(`The Array after Change ${numbers}`)
console.log(`The Length after pop() is : ${numbers.length}`)
Array.push()
The push()
method adds one or more elements to end the array and returns the new length of the array
array.push(element1, element2,...,elementN)
const numbers = [1,2,3,4,5]
console.log(`The Length before push() is : ${numbers.length}`)
numbers.push(6,7,8)
console.log(`The Array after Change ${numbers}`)
console.log(`The Length after push() is : ${numbers.length}`)
Array.reduce()
The reduce()
method executes a user-supplied "reducer" callback function on every element of the array. It works on each element step by step and in order. It does not change the original array
reduce((previousValue, currentValue, currentIndex, array) => { /* … */ } )
const numbers = [1,2,3,4,5]
console.log(numbers.reduce((ele, sum) => sum + ele))
Array.reverse()
The reverse() method reverse an array and returns the reference to same array, i.e it modifies the original array.
const numbers = [1,2,3,4,5]
console.log(numbers)
numbers.reverse()
console.log(numbers)
Array.shift()
This method removes the first element from the array and returns that element.
const numbers = [1,2,3,4,5,6,7]
console.log(`The Length before shift() is : ${numbers.length}`)
const shifted = numbers.shift()
console.log(`The removed element : ${shifted}`)
console.log(`The Array after Change ${numbers}`)
console.log(`The Length after shift() is : ${numbers.length}`)
Array.unshift()
The unshift()
method adds one or more elements to the beginning the array instead at the last like push()
and like push()
it also changes the length.
const numbers = [1,2,3,4,5]
console.log(`The Length before unshift() is : ${numbers.length}`)
numbers.unshift(6,7,8)
console.log(`The Array after Change: ${numbers}`)
console.log(`The Length after unshift() is : ${numbers.length}`)
Array.slice()
The slice()
method returns a copy of the portion of an array into new array object selected from start
to end
, where start
and end
are index of the items of the array. This method does not modified the original array
slice()
slice(start)
slcie(start,end)
const numbers = [1,2,3,4,5,6,7,8]
const sliced = numbers.slice(2,4)
console.log(numbers)
console.log(sliced)
Array.some()
The some()
method tests a condition just like every()
method but instead of matching the condition to all elements like it did in every()
, in some()
we just check if some elements match the condition, if some elements match then we return true
If no element matches we return false
const isEven = (value) => value%2===0
const arr1 = [2,4,6,8]
const arr2 = [2,4,6,7]
const arr3 = [1,3,5,7]
console.log(arr1.some(isEven))
console.log(arr2.some(isEven))
console.log(arr3.some(isEven))
Array.sort()
This method sorts the array like the name suggests, it can sort both numbers and alphabets. We can also given a sorting condition. The default sorting condition is ascending.
const numbers = [1,2,6,7,8,34,5,21,5,2,1,0,12,45]
const alpha = ['r','t','v','f','a','b']
console.log(numbers.sort((a,b) => a-b))
console.log(alpha.sort())
Array.splice()
This method is used to change chunks of array and resize the array while changing the original array completely. We can delete the items or change their value using splice.
General Syntax
splice(start, deleteCount, item1, item2, itemN)
const numbers = [1,2,3,4,5,6,7]
const numbers1 = [1,2,3,4,5,6,7]
numbers.splice(2,3)
numbers1.splice(2,2,'a','4')
console.log(numbers)
console.log(numbers1)