JavaScript Arrays Made Easy!
An in depth guide on arrays in JavaScript
What is an Array?
An array is a data structure that is used to store multiple values in a single variable. Each item in an array has a number attached to it called an index and it is used to access the items in an array. In Javascript, arrays start with an index zero.
An example of an array that stores multiple integer values is given below
let myArray = [1, 2, 3, 4, 5];
Note: Unlike other programming languages in Javascript an Array can hold items with different data types.
const details = ["John", 25, { Alive: true }, function() { alert('Hello!'); }];
How to create an Array and access Array elements?
There are 2 ways of creating an empty Array in Javascript
Using Array literal
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets([]).
This is the easiest way to create an array in Javascript
Syntax:
let arrayName = [] console.log(array) // []
Using
new
keywordSyntax:
let array = new Array(); console.log(array) // []
The first method is widely used to create arrays. You can supply initial values to an Array within the square brackets while creating an Array. For example
let fruits = ["Orange", "Grapes", "Mango", "Apple"];
As I told you earlier each array item is attached to a number called an index. We can use this index to access the item by using its index inside the square bracket as shown below
console.log(fruits[0]) // Orange
console.log(fruits[1]) // Grapes
console.log(fruits[2]) // Mango
console.log(fruits[3]) // Apple
Important Array Methods
push()
This method is used to insert one or more elements into the end of an array and returns the length of the array. It modifies the original array.
let fruits = ["Orange", "Grapes", "Mango"]; console.log(fruits.push("Banana")); // 4 console.log(fruits); // [ 'Orange', 'Grapes', 'Mango', 'Banana' ]
You can also push multiple values at once.
pop()
This method removes the last element of an array and returns that element. It modifies the original array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.pop()); // Banana console.log(fruits); // [ 'Orange', 'Grapes', 'Mango' ]
shift()
This method removes the first element of an array and returns that element. It modifies the original array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.shift()); // Orange console.log(fruits); // [ 'Grapes', 'Mango', 'Banana' ]
unshift()
This method is used to add one more element to the beginning of the array and it returns the new length of the array. It modifies the original array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.unshift("Cherry")); // 5 console.log(fruits); // ['Cherry', 'Orange', 'Grapes', 'Mango', 'Banana']
indexOf()
This method returns the index of the first occurrence of the given element in an array and returns -1 if the element is not found.
let fruits = ["Orange", "Grapes", "Mango", "Banana", "Mango"]; console.log(fruits.indexOf("Mango")); // 2
lastIndexOf()
This method returns the index of the last occurrence of the given element in an array and returns -1 if the element is not found.
let fruits = ["Orange", "Grapes", "Mango", "Banana", "Mango"]; console.log(fruits.lastIndexOf("Mango")); // 4
reverse()
This method reverses an array in place and returns a reference to the same array. The last element becomes the first element and the first element becomes the last. It modifies the original array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.reverse()); // ['Banana', 'Mango', 'Grapes', 'Orange']
includes()
This method returns true if it finds an element in an array and if the element is not present in the array it returns false.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.includes("Mango")); // ture
concat()
This method merges two or more arrays and returns the merged array. It does not modify the original array.
const arrayOne = [1, 2, 3]; const arrayTwo = [4, 5, 6]; const mergedArray = arrayOne.concat(arrayTwo); console.log(mergedArray); // [ 1, 2, 3, 4, 5, 6]
sort()
This method is used to sort all the elements of an array in place and returns a reference to the same array. It modifies the original array.
const arr = [1, 5, 2, 8]; console.log(arr.sort()); //[ 1, 2, 5, 8 ]
fill()
This method fills an array with a static value and returns a modified array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.fill("Fruit"));// ['Fruit', 'Fruit', 'Fruit', 'Fruit']
slice()
This method returns a new array containing all the elements of an array between the specified start index and end index. It does not modify the original array.
let fruits = ["Orange", "Grapes", "Mango", "Banana"]; console.log(fruits.slice(2, 4)); // [ 'Mango', 'Banana' ] console.log(fruits); // ['Orange', 'Grapes', 'Mango', 'Banana']
some()
This method returns true if at least one element in an array satisfy the given condition else it returns false.
const arr = [1, 2, 3, 4]; console.log(arr.some((num) => num > 2)); // true
every()
This method returns true if all the elements in an array satisfy the given condition else it returns false.
const arr = [1, 2, 3, 4]; console.log(arr.every((num) => num < 0)); // false
find()
This method returns the first element in an array that satisfies the given condition.
const arr = [1, 2, 3, 4, 5, 6]; console.log(arr.find((num) => num > 4)); // 5
findIndex()
This method returns the index of the first element in an array that satisfies the given condition.
const arr = [1, 2, 3, 4, 5, 6]; console.log(arr.findIndex((num) => num > 4)); // 4
join()
This method adds all the elements of an array into a string, separated by the specified separator string
const fruitName = ["O", "r", "a", "n", "g", "e"]; console.log(fruitName.join("")); // Orange
forEach()
This method is used to loop over the array by executing a provided callback on each element of the array.
const arr = [4, 5, 6]; arr.forEach((item) => { console.log(item); }) // 4 // 5 // 6
map()
This method returns a new array by executing a provided callback on each element of the array. It does not modify the original array.
const arr = [1, 2, 3, 4]; const newArr = arr.map((item) => item + 10); console.log(newArr); //[ 11, 12, 13, 14 ]
filter()
This method returns a new array containing elements of an array that passes a specified condition. It does not modify the original array.
const arr = [1, 2, 3, 4, 5, 6]; const filteredArr = arr.filter((item) => item % 2 == 0); console.log(filteredArr); // [ 2, 4, 6 ]
reduce()
This method executes a reducer function on each array element and returns a single value which is the result of the reducer function. It does not modify the original array.
const arr = [1, 2, 3, 4, 5, 6]; const reducedValue = arr.reduce((sum, currentValue) => sum + currentValue); console.log(reducedValue); // 21
Thank you for reading the article. If you liked it please give a ❤️ and share your valuable feedback in the commets.