In web development, JavaScript Arrays are used to store and organize data efficiently. In this blog post, we’ll learn about the arrays, and methods of accessing, manipulating and looping through arrays.
What are Arrays?
In JavaScript, Arrays are like containers that can hold multiple items such as numbers, strings, objects, or even other arrays. Each item in the array has a number assigned to it, starting from 0 and can be accessed and manipulated using numerical indices.
Creating Arrays
We can create arrays in two ways:
- Using array literal:
We can create arrays using array literal[]
i.e. by defining the array elements within square brackets [ ]. For example:
//Example:1
const fruits = ["apple", "banana", "orange", "grapes"];
//Example:2
const numbers = [8, 9, 3];
//Example:3
const data = ["apple", "banana", 9, 5];
- Using the
new
keyword:
The other method to creating arrays is by usingnew
keyword.
const fruits = new Array("apple", "banana", "orange", "grapes");
Accessing Elements in Arrays
We can access array elements using numerical indices(0, 1, 2…).
Note: The index of an array starts with 0.
const fruits = ["apple", "banana", "orange", "grapes"];
console.log(fruits[0]); //apple
console.log(fruits[1]); //banana
Finding the Length of the Array
We can find the length of the array (number of elements in an array) using length
property.
const numbers = [1, 2, 3, 4, 5, 6, 7];
const arrLength = numbers.length
console.log(arrLength) // 7
Changing Elements in the Array
We can change the elements of an array by accessing their index value. For example:
const fruits = ["apple", "banana", "orange", "grapes"];
//this will change the element at index 1
fruits[1] = "Plum";
console.log(fruits); //['apple', 'Plum', 'orange', 'grapes']
We can also add a new element to the array. For example:
const fruits = ["apple", "banana", "orange", "grapes"];
//this will add the element at index 4
fruits[4] = "Plum";
console.log(fruits); //['apple', 'banana', 'orange', 'grapes', 'Plum']
Array methods
pop()
: This method removes the last element of the array and returns the removed element.
This method updates the original array.
const numbers = [1, 9, 13, 7];
const removedElement = numbers.pop();
console.log(removedElement); // 7
console.log(numbers); // [1, 9, 13]
push()
: This method adds a new element at the end of the array and returns the new array length.
This method modifies the original array.
const numbers = [1, 9, 13, 7];
const newElement = numbers.push(2);
console.log(numbers); // [1, 9, 13, 7, 2]
console.log(newElement); //5 (new array length)
shift()
: This method removes the first element of the array and returns the removed element.
const numbers = [1, 9, 13, 7];
const removedElement = numbers.shift();
console.log(numbers); // [9, 13, 7]
console.log(removedElement ); // 1
unshift()
: This method adds a new element at the beginning of the array and returns the new array length.
const numbers = [1, 9, 13, 7];
const newElement = numbers.unshift(2);
console.log(numbers); // [2, 1, 9, 13, 7]
console.log(newElement); //5 (new array length)
toString()
: This method converts an array into a string of comma-separated values.
const numbers = [1, 9, 13, 7];
const numbers1 = numbers.toString();
console.log(numbers1); // 1,9,13,7
join()
: This method joins all the elements of an array using a given separator.
const numbers = [1, 9, 13, 7];
const numbers1 = numbers.join("-");
const numbers2 = numbers.join("!");
console.log(numbers1); // 1-9-13-7
console.log(numbers2); // 1!9!13!7
delete
: Elements of an array can be deleted using thedelete
operator.delete
operator leavesundefined
holes in the array.
const numbers = [1, 9, 13, 7];
delete numbers[3];
console.log(numbers); // [1, 9, 13, empty]
console.log(numbers[3]); // undefined
concat()
: This method creates a new array by joining two or more given arrays.
const arr1 = [1, 9, 13, 7];
const arr2 = ["a", "f", "i"];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 9, 13, 7, 'a', 'f', 'i']
sort()
: This method sorts the array elements alphabetically.
const arr = ["a", "z", "s"];
arr.sort();
console.log(arr); // ['a', 's', 'z']
const colors = ["red", "blue", "white"];
colors.sort();
console.log(colors); // ['blue', 'red', 'white']
splice()
: This method is used to add, remove, or replace elements at any position within an array.
const numbers1 = [1, 8, 13, 4, 15];
numbers1.splice(2, 1); // Removes 1 element at index 2
console.log(numbers1); // [1, 8, 4, 15]
const numbers2 = [1, 78, 13, 54, 15];
numbers2.splice(1, 0, 6, 7); // Adds 6 and 7 at index 1
//basic syntax: array.splice(position to add new element, number of elements to remove, elements to be added)
console.log(numbers2); // [1, 6, 7, 78, 13, 54, 15]
slice()
: This method slices out a part of an array and returns a new array.
//Example:1
const array1 = [1, 5, 6];
const newArray1 = array1.slice(1); // starts at index 1 and slice upto the end
console.log(newArray1); // [5, 6]
//Example:2
const array2 = [1, 34, 16, 5, 13];
const newArray2 = array2.slice(1, 3); // starts at index 1 and slice upto index (3-1)
console.log(newArray2); // [34, 16]
//Example:3
const array3 = ["red", "orange", "blue", "green", "white"];
const newArray3 = array3.slice(2, 4); // starts at index 2 and slice upto index (4-1)
console.log(newArray3); // ['blue', 'green']
reverse()
: This method reverses the elements of the array.
const colors = ["red", "orange", "blue", "green", "white"];
colors.reverse();
console.log(colors); // ['white', 'green', 'blue', 'orange', 'red']
indexOf()
: This method searches an element of an array and returns the position of the element.
const colors = ["red", "orange", "blue", "green", "white"];
console.log(colors.indexOf("blue")); // 2
console.log(colors.indexOf("orange")); // 1
find()
: This method returns the first value of an element based on a condition.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumber = numbers.find(num => num % 2 === 0);
console.log(evenNumber); // 2
const numbers2 = [4, 3, 6];
const evenNumber2 = numbers2.find(num => num % 2 === 0);
console.log(evenNumber2); // 4
findIndex()
: This method returns the first index of an element based on a condition.
const numbers = [1,3, 13, 5, 2, 6];
const evenNumber = numbers.findIndex(num => num % 2 === 0);
console.log(evenNumber); // 4
findLastIndex()
: This method returns the last index of an element based on a condition.
const numbers = [1,3, 13, 5, 2, 6, 18, 17];
const evenNumber = numbers.findLastIndex(num => num % 2 === 0);
console.log(evenNumber); // 6
includes()
: This method checks whether an element is present in the array or not.
const numbers = [1,3, 13, 5, 2, 6];
console.log(numbers.includes(5)); // true
console.log(numbers.includes(7)); // false
Looping through Arrays
Arrays can be looped through using the following methods:
for()
: Arrays can be looped through using the for loop.
const colors = ["red", "orange", "blue", "green", "white"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Output:
red
orange
blue
green
white
forEach()
: This loop calls a function once for each element of the array.
const colors = ["red", "orange", "blue", "green", "white"];
colors.forEach(color => console.log(color));
Output:
red
orange
blue
green
white
map()
: This method creates a new array by performing a function on each element of the array.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
filter()
: This method creates a new array by filtering array elements based on a condition.
const numbers = [1, 62, 13, 44, 5];
const filteredNumbers = numbers.filter(num => num > 25);
console.log(filteredNumbers); // [62, 44]
reduce()
: This method reduces the array to a single value by performing a function on each element of the array.
const numbers = [1, 62, 13, 44, 5];
const reducedNumbers = numbers.reduce((total, num)=> total + num);
console.log(reducedNumbers); // 125
Explanation for the above code:
First the function will take the starting two values of the arrays (1 and 62) and add them.
1 + 62 => 63
Then it will add 63 to the next value of the array 13.
63 + 13 => 76
After that it will add 76 to the next value of the array 44.
76 + 44 => 120
And lastly it will add 120 to next value of the array 5.
120 + 5 => 125
array.from()
: This method creates an array object from any other object.
Array.from("ABCDE"); // ['A', 'B', 'C', 'D', 'E']
for...of
: This loop can be used to get the values from an array.
const colors = ["red", "orange", "blue", "green", "white"];
for (color of colors){
console.log(color);
}
Output:
red
orange
blue
green
white
for...in
: This loop can be used to get the keys from an array.
const colors = ["red", "orange", "blue", "green", "white"];
for (color in colors){
console.log(color);
}
Output:
0
1
2
3
4
Conclusion
Arrays are fundamental data structures that allow to store and organize multiple items efficiently. They can hold various data types, including numbers, strings, objects, and even other arrays. Accessing and manipulating array elements is done through numerical indices, starting from 0.
In this blog post, we have learned about various aspects of creating arrays, accessing elements, finding the length, changing elements, and using important array methods like pop()
, push()
, shift()
, unshift()
, toString()
, join()
, delete
, concat()
, sort()
, splice()
, slice()
, reverse()
, indexOf()
, find()
, findIndex()
, and includes()
.
Also, how to loop through arrays using different methods such as for
, forEach
, map
, filter
, reduce
, Array.from
, for...of
, and for...in
.
Thanks for reading.
Keep Coding!
For more content like this click here!
Check out toast.log, a browser extension that lets you see errors, warnings, and logs as they happen on your site — without having to open the browser’s console. Click here to get a 25% discount on toast.log.