Arrays are the most fundamental building blocks of any program. An array is nothing but a list of elements. It is the most commonly used and easy-to-understand data structure. Different programming languages have different ways of implementing arrays in them. Today we will discuss Arrays and its methods in JavaScript.
Arrays in JavaScript
Arrays in Javascript are defined by using [ ]
brackets and elements inside the array are separated by ,
. It is a single variable that behaves like a list of elements.
An array can hold elements with different data types i.e we can store a number, a string, a boolean value, etc inside a single array.
For example,
let arr = [1, "Hello", "world", true, [3,4] ];
Position of an element in an array can be accessed using an index. The index is nothing but a number that denotes the position of that element in the array. In the programming world counting the position of an element in an array starts from 0 which means that the position of the first element in an array is 0 and hence the position of the last element is (size of array)-1
.
Create an array
There are two ways to create an array in JavaScript.
let grocery = ["bread ", "milk ", "eggs ", "chips "]; //method1
OR
let grocery= new Array("bread ", "milk ", "eggs", "chips" ); //method2
The first method is simply creating an array by declaring a variable with elements inside []
brackets and the second method is by using JavaScript's Array() constructor.
Access elements of an array
To access an individual element from an array, the index of that element can be used.
let grocery = ["bread", "milk", "eggs", "chips"];
let milk= grocery[1];
console.log(milk);
/*
Output is
"milk"
*/
Remember index in an array starts from 0, so to access "milk" from the array above we need to give the index as 1. We can replace or modify an element of an array by using the index of that element. Let's replace "chips" with "coffee". We know the index of "chips" so we can replace it as shown in the example below.
let grocery = ["bread", "milk", "eggs", "chips"];
grocery[3] = "coffee";
console.log(grocery);
Output
["bread", "milk", "eggs", "coffee"]
Size of an array
To get the size of an array we can use .length
property.
This returns the number of elements present in the array.
let grocery = ["bread", "milk", "eggs", "chips"];
let size = grocery.length;
console.log(size);
Output
4
length
is a property and not a function, hence remember not to use ()
after it like .length()
as it will throw you an error.
Array Methods
1. push()
Adds a new element at the end of an array and returns the size of the updated array.
Syntax
push(element)
Example
let grocery = ["bread", "milk", "eggs", "chips"];
let updatedSize = grocery.push("apples");
console.log(updatedSize);
console.log(grocery);
Output
5
[ 'bread', 'milk', 'eggs', 'chips', 'apples' ]
2. pop()
Removes an element from the end of an array and returns the deleted element.
So using pop()
on our grocery list will delete the last item from the list.
Example
let grocery = ["bread", "milk", "eggs", "chips"];
let deletedItem= grocery.pop();
console.log(deletedItem);
console.log(grocery);
Output
chips
[ 'bread', 'milk', 'eggs' ]
3. shift()
Removes the element from start of an array and returns the removed element.
It removes the first element from the array and shifts all elements to one position left in the array.
So using shift()
on our grocery list will delete the first item from the list.
Example
let grocery = ["bread", "milk", "eggs", "chips"];
let deletedItem= grocery.shift();
console.log(deletedItem);
console.log(grocery);
Output
bread
[ 'milk', 'eggs', 'chips' ]
4. unshift()
Adds one or more elements to the start of an array and returns new length of the array.
It shifts existing elements to the right and adds new elements at the start, hence it changes the index of all elements in the array.
Using this method is not recommended when the size of array is huge as its a heavy operation because it has to shift each element in the array. Instead use push()
Syntax
unshift(element1, element2,......, elementN)
Example
let grocery = ["bread", "milk", "eggs", "chips"];
let updatedSize = grocery.unshift("apples");
console.log(updatedSize);
console.log(grocery);
Output
5
[ 'apples', 'bread', 'milk', 'eggs', 'chips' ]
5. concat()
Merges two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Syntax
concat()
concat(value0)
concat(value0, value1)
concat(value0, value1, /* … ,*/ valueN)
Example
let grocery = ["bread", "milk", "eggs", "chips"];
let newGrocery = ["butter", "yoghurt", "almonds"];
let updatedList = grocery.concat(newGrocery);
console.log(updatedList);
Ouput
[
'bread', 'milk',
'eggs', 'chips',
'butter', 'yoghurt',
'almonds'
]
6. slice()
Returns a portion of an existing array as a new array. It doesn't modify the existing array.
Requires start
and end
values as arguments where start
is index of element from which your required group of elements start and end
is the index of element which is next to the last element of your required group of elements. This means that the element which is having end
will not be included.
When only start
value is provided as an argument, it returns a group of elements starting from index value ofstart
to the end of the array. And if no argument is passed, it returns whole array.
Syntax
slice()
slice(start)
slice(start, end)
Example
let grocery = ["bread", "milk", "eggs", "chips", "butter", "yoghurt", "almonds"];
// values from 1 to 3
let slicedList = grocery.slice(1,4);
console.log(slicedList);
// values from 4 to end of array
let slicedList2 = grocery.slice(4);
console.log(slicedList2);
Output
[ 'milk', 'eggs', 'chips' ]
[ 'butter', 'yoghurt', 'almonds' ]
7. splice()
Modifies existing array by deleting or replacing existing elements or by adding new elements. Returns an array containing the deleted elements.
Syntax
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, element1)
splice(start, deleteCount, element1, element2, elementN)
start
parameter denotes the index at which modification of array should start.
deleteCount
parameter denotes number of elements to be removed from start
.
element1, ......, elementN
denotes elements to be added from start
.
Example
let grocery = ["bread", "milk", "eggs"];
//adds coffee at position 1 and deletes 0 elements
grocery.splice(1, 0, "coffee");
console.log(grocery);
//output - [ 'bread', 'coffee', 'milk', 'eggs' ]
// deletes 1 element from index 2 and adds 2 elements from index 2
grocery.splice(2, 1, "tea", "butter")
console.log(grocery);
//output - [ 'bread', 'coffee', 'tea', 'butter', 'eggs' ]
// remove all elements from index 1
grocery.splice(1);
console.log(grocery);
//output - [ 'bread' ]
8. toString()
Returns a string representing the specified array and its elements. The elements are separated using a comma ,
in the string.
let grocery = ["bread", "milk", "eggs"];
console.log(grocery.toString());
Output
bread,milk,eggs
9. join()
Works similar to toString()
, but here we can use a different delimiter or separator to separate the elements in the returned string.
Syntax
join()
join(separator)
When no argument is passed elements are separated by a comma ,
.
Example
let grocery = ["bread", "milk", "eggs"];
console.log(grocery.join());
console.log(grocery.join(' & '));
console.log(grocery.join(' * '));
Output
bread,milk,eggs
bread & milk & eggs
bread * milk * eggs
10. reverse()
Reverses the order of elements of an array. Does not return a new array, modifies the existing one.
let grocery = ["bread", "milk", "eggs"];
console.log(grocery.reverse());
Output
[ 'eggs', 'milk', 'bread' ]
11. sort()
Sorts the elements of an array in place, i.e. modifies the existing array instead of returning a new copy. By default sorts elements alphabetically or in ascending order.
let grocery = ["bread", "milk", "eggs", "coffee"];
console.log(grocery.sort());
Output
[ 'bread', 'coffee', 'eggs', 'milk' ]
12. includes()
Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
Syntax
includes(searchElement)
includes(searchElement, fromIndex)
Example
let grocery = ["bread", "milk", "eggs", "coffee"];
console.log(grocery.includes("milk"));
// start searching from index 2
console.log(grocery.includes("milk", 2));
Output
true
false
13. indexOf()
Returns the position of the first occurrence of a value in the array. If the value cannot be found, -1 is returned. This method has two parameters the item we want to search and the position from where we want to start the search in the start. If only a single parameter is passed it will be treated as the element to search and it will be searched from the start of the array.
Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex)
Example
let grocery = ["bread", "milk", "eggs", "coffee"];
//expected output is 1. starts searching from index 0
console.log(grocery.indexOf("milk"));
//expected output is -1 as it starts searching from index 2
console.log(grocery.indexOf("milk", 2));
Output
1
-1
14. copyWithin()
Shallow copies portion of an array to another location in the same array.
Note: This method doesn't change the size of the array, it replaces existing elements from the array.
Syntax
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
target
is the index where the content should be copied. If greater than or equal to the length of the array nothing will be copied.
start
is the index to start selecting elements to be copied.
end
is the index where the selection of elements to be copied should end.
Example
let grocery = ["bread", "milk", "eggs", "coffee", "apples"];
// copy elements form 3 to 4 to location at index 1
console.log(grocery.copyWithin(1,3,4));
// copy elements from 3 to end of the array to location at index 1
console.log(grocery.indexOf(1, 3));
Output
[ 'bread', 'coffee', 'eggs', 'coffee', 'apples' ]
[ 'bread', 'coffee', 'apples', 'coffee', 'apples' ]
15. find()
Returns the first element found from the array which satisfies the given condition. Takes a callback function as an argument that executes on each value in the array.
Example
let numbers = [5,10, 44, 17, 24, 32, 74]
let greaterThanTen = numbers.find(num => num> 10);
console.log(greaterThanTen);
Output
44
16. findIndex()
Works similar to find()
, just returns the index of the element which satisfied the condition. -1 is returned if no element satisfies the condition.
Example
let numbers = [5,10, 44, 17, 24, 32, 74]
let greaterThanTen = numbers.findIndex(num => num> 10);
console.log(greaterThanTen);
Output
2
17. every()
Tests whether all elements in the array satisfy the condition or not. Returns true if all elements match the condition and false if any of the elements fails to satisfy the condition.
Example
let ages = [19,22,43,35,60,51,32]
let areAllAdults = ages.every(age => age> 18);
console.log(areAllAdults);
Output
true
18. some()
Tests whether at least one element in the array satisfies the condition or not. Returns true if at least one element matches the condition and false if none of the elements satisfy the condition.
Example
let ages = [15,22,43,35,60,10,8]
// check if there are any adults in the list
let isAnyAdult = ages.some(age => age> 18);
console.log(isAnyAdult);
Output
true
19. map()
Creates a new array populating results achieved by applying the operation provided in the function to each element of the array. Takes a callback function as an argument.
Example
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let squares = numbers.map(num => num * num);
console.log(squares);
Output
[
1, 4, 9, 16, 25,
36, 49, 64, 81
]
20. filter()
Returns an array of elements that satisfy the condition provided inside the callback function. So basically it filters the elements of the array. Example
// get list of ages which are greater than 18
let ages = [19,22,43,35,60,51,32]
let allAdults = ages.filter(age => age> 18);
console.log(allAdults);
Output
[
19, 22, 43, 35,
60, 51, 32
]
21. forEach()
Executes a provided function once for each array element. Basically, it just works like a simple for loop.
Example
let grocery = ["bread", "milk", "eggs", "coffee"];
// print grocery list
grocery.forEach(item => console.log(item));
Output
bread
milk
eggs
coffee
These are some of the most commonly used methods of arrays in javascript. There are some more methods of arrays which you can check here.
Hope this article helped you to understand Arrays in JavaScript and its methods better. Please do like this article or put a comment to share your feedback.
Happy Coding 🧑💻