JavaScript Array

JavaScript Array

ยท

13 min read

The array is the most used data structure of any programming language, so then what is Array? The array is a collection of items or elements. It is like a container where you can store multiple values. in JavaScript Array is denoted by square brackets [] , opening square brackets indicate the start of the array and closing square brackets indicate the end of the array. Inside the square brackets, we can store multiple values separating them with comma , . This is how an array in JavaScript looks like let fruits = ["apple", "grapes", "banana", "orange", "guava"]; Here we have a list of fruits and we are storing them in a fruits variable.

In an Array, all the items of an array are known as elements, and elements in an Array are given a unique position known as an index we will talk more about the index later, so in the above example, the names of fruit are elements of the fruit array. In JavaScript Array, we can store values of any type, values can be anything e.g string, boolean, number, etc we can even store an array inside an array. Here are a few more examples of JavaScript Array.

let arr1 = []
let fruits = ['apple', 'grapes', 'banana', 'orange', 'guava'] // array of strings
let even_numbers = [2,4,6,8,10] // array of numbers
let vowels = ['a','e','i','o','u'] // array of characters
let arr2 = ['hello', "2", 76, 8.23] // array of mixed values
let arr3 = ["How are You", ["hi", 4.5, 9], 98] // array of mixed values

How to create an Array in JavaScript

We can create an array by just assigning a pair of square brackets to a variable let's look at this example let fruits = []; This fruit array has no element inside it, so it is known as an empty array. There is also another way to create an array in JavaScript but it's not used much.let fruits = new Array(); this is also an empty array. take a look at the below code and you will know how we add elements to this Array.

let fruits = []; // empty array
let fruits = ['apple', 'grapes', 'banana', 'orange', 'guava']

let fruits = new Array(); .// not used much
let fruits = new Array("apple", "grapes", "banana", "orange", "guava");

More on Index

An Array is an ordered collection of elements and an element in an array is given a unique position known as an Index, we use this index to access individual elements from the array. The index starts from 0 and goes up the length of the array - 1. The length of the array is the number of elements in the array. let's look at our fruits array let fruits = ['apple', 'grapes', 'banana', 'orange', 'guava'] in this fruits array, there are five elements so the length of the array is 5. So the index of the array of fruits starts from 0 and goes up to 4, apple is at an index of 0, and guava is at the index of 4. Take a look at the below picture you will get a more clear picture of how the index works.

Access Element of an Array Using Index.

We have already learned that we can access an individual element using the index, to access individual elements from an array we use this syntax.

arrayName[index]

Take a look at the example below it will make more sense.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// get first element from the fruits array
console.log(fruits[0]); // first element is always at index 0

// get second element from the fruits array
console.log(fruits[1]);

// get third element from the array
console.log(fruits[2]);

// get last element from the fruits array
console.log(fruits[4]); // not recommended

Getting the Last element of an Array

Getting the last element from an array is the same as getting the element at any other position in an array, take a look at the example below.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// get last element from the fruits array
console.log(fruits[4]); // not recommended

In the above example, you can see that guava at index 4 is the last element from the fruits array and we are able to access it just like any other element on any position, yes but think of a situation when you don't have any idea about the length of the array, you don't know at what index the last element of the array is going to be, this method works only when the array is short. Let's learn about the other method.

Remember I mentioned that the index starts from 0 and goes up to the length of the array -1, so if the length of the array is 10 then the index will start from 0 and will go up to 9, if we can somehow find the length of the array then it will be easy to find the last index of the array.

length of the array:-

lenght of the array is number of elemement in the array. I f there are 5 elements in the array then lenght of the array is 5.

JavaScript comes with inbuilt property to find length of the array, this is the syntax we use to find the lenght of the array.

arrayName.length

this return us the lenght of the array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

console.log(fruits.length); // output -> 5

Now we know how to find the length of the array so to access the last element of the array we can use fruits.length - 1 it will give us the last index of the array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// just for example gives us last index of any array
console.log(fruits.length - 1); // output -> 4

// get the last element from the fruits array
console.log(fruits[fruits.length - 1]); // output -> 4

Modifying Element of An Array Using Index.

We can access elements of an array using the index, we can also use the index to modify an array, take a look at the below syntax.

arrayName[index] = "value"

Here are a few more examples.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// Remove banana from index 2 and add Papaya at index 2
fruits[2] = "Papaya"; // this will replace banana with papaya
console.log(fruits); // o/p->[ 'apple', 'grapes', 'Papaya', 'orange', 'guava' ]

let newList = [];

// Add element to the newList

newList[0] = "Pear";
newList[1] = "Strawberry";
newList[2] = "Watermelon";
console.log(newList); // o/p -> [ 'Pear', 'Strawberry', 'Watermelon' ]

Array Methods

JavaScript comes with lots of array methods, we can use this method to make perform different tasks and make our work easy. In this section of the article, we will talk about some of the most used array methods.

push()

push() method is to add one or more elements at the end of the array, it also returns us the new length of the array after adding new elements.

arrayName.push("element") when adding single element

arrayName.push("element","element2") adding multiple element

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
let newArrayLength = fruits.push("Pear"); // this will return new array length 
console.log(fruits); // o/p -> [ 'apple', 'grapes', 'banana', 'orange', 'guava', 'Pear' ]

pop()

pop() method removes the last element from the array and also returns the removed element. We use this method when we want to remove the last element from the array and use the returned element later.

Syntax:

arrayName.pop()

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
let poppedElement = fruits.pop(); // last element removed from the fruits array will be stored in poppedElement Variable
console.log(poppedElement); // o/p -> guava
console.log(fruits); // o/p [ 'apple', 'grapes', 'banana', 'orange' ]

shift()

shift() method removes the first element i.e element at index 0, from the array and returns the removed element.

Syntax:

arrayName.shit()

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
// fruits.shift(); // use this when you don't want to store the removed element
let removedElement = fruits.shift(); // removes the first element from the fruits array and store the removed element
// fruits.shift();
console.log(removedElement); // o/p -> apple i.e first element of fruits array
console.log(fruits); // o/p -> [ 'grapes', 'banana', 'orange', 'guava' ]

unshift()

unshift() method is used to add one or more elements at the start of the array, it also returns the new length of the array after adding the element.

Syntax:

arrayName.unshift("element") // single element

arrayName.unshift("element1","element2") // multilple element

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// Add "Pear" at the start of the array
fruits.unshift("Pear"); // adding one element
console.log(fruits); // o/p -> [ 'Pear', 'apple', 'grapes', 'banana', 'orange', 'guava' ]

// Add "Strawberry" and "Papaya" at the beginning  of the array
fruits.unshift("Strawberry", "Papaya"); // adding multiple element at the beginning of the array
console.log(fruits); // o/p [ 'Strawberry',  'Papaya','Pear', 'apple', 'grapes', 'banana', 'orange', 'guava' ]

// Add "PineApple at the start of the array  and store the new length of the array in  newLength variable"
let newLength = fruits.unshift("PineApple");
console.log(newLength); // o/p ->    9

sort()

sort() method is used to sort the elements of the array. It sorts the strings in alphabetical order and numbers in ascending order. sort() the method doesn't use any extra space or use another array for sorting, it overwrites the original array and returns it.

Syntax:

arrayName.sort()

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
fruits.sort();
console.log(fruits); // o/p -> [ 'apple', 'banana', 'grapes', 'guava', 'orange' ]

let marks = [23, 66, 22, 96.4, 84.3];
// displaying the returned array
console.log(marks.sort()); // o/p -> [ 22, 23, 66, 84.3, 96.4 ]

reverse()

reverse() method is used when we want to reverse the original order of the array. reverse() method also doesn't use any extra space or use another array for sorting, it overwrites the original array and returns it.

Syntax:

arrayName.reverse()

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
fruits.reverse();
console.log(fruits); // o/p -> [ 'guava', 'orange', 'banana', 'grapes', 'apple' ]

let marks = [23, 66, 22, 96.4, 84.3];

// displaying the returned value.
console.log(marks.reverse()); // o/p -> [ 84.3, 96.4, 22, 66, 23 ]

splice()

splice() method is used to remove, replace or add elements to the array. It returns an array of removed items.

Syntax:

arrayName.splice(startIndex,deleteCount, item1, item2, n_item)

startIndex-> The index from where you want to modify the array

deleteCount(optional) -> It is the number of element you want to delete.

item1,item2,n_item(optional) ->Elements you want to add to the start index. if this is not specfied,splice() wll only remove elements from the array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// Add PineApple at index 1
fruits.splice(1, 0, "PineApple"); // no items is being removed so it will remove empty array.
console.log(removedFruits); // o/p ->[]
console.log(fruits); // o/p -> [ 'apple', 'PineApple', 'grapes', 'banana', 'orange', 'guava' ]

// now our fruits array contains following elements [ 'apple', 'PineApple', 'grapes', 'banana', 'orange', 'guava' ]

// Add 2 Elements "Watermelon" and "Strawberry"  starting at index 2
fruits.splice(2, 0, "Watermelon", "Strawberry");
console.log(fruits);

// Remove all the newly added elements from the array and store the removed element in a variable.
let removedFruits = fruits.splice(1, 3);
console.log(removedFruits); // 0/p -> [ 'PineApple', 'Watermelon', 'Strawberry' ]
console.log(fruits);  // o/p ->[ 'apple', 'grapes', 'banana', 'orange', 'guava' ]

slice()

slice() method is used when we want a copy of an array's portion. It returns a copy of a small portion of the array from the original array without modifying the original array.

Syntax:-

arrayName.slice(startIndex,stopIndex)

startIndex(optional) -> Index from where you want to start the slicing.

stopIndex(optional) -> Index at where you want to stop slicing. Rembember stopIndex is always exclusive element at this index is not included in the returned array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// get a new array of "grapes", "banana" and "orange"
let newSlicedList = fruits.slice(1, 4); // stop index is 4 instead of 3 because stop index is exclusive.
console.log(newSlicedList); // o/p ->[ 'grapes', 'banana', 'orange' ]
console.log(fruits); // o/p -> [ 'apple', 'grapes', 'banana', 'orange', 'guava' ]

console.log(fruits.slice()); // if no parameter is passed it slice the array from start to end

concat()

concat() method is used to join two or more arrays or values. It does not modify the original array instead it returns a new array with the values from both the array.

Syntax:

arrayName.concat(array/value,array/value)

array/value: can be a single value or an array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];
let anotherFruitsArray = ["PineApple", "Watermelon", "Strawberry"];

// create a new array which has all the elements from both the array.
let newJoinedArray = fruits.concat(anotherFruitsArray);
console.log(newJoinedArray); // ["apple","grapes", "banana", "orange","guava", "PineApple","Watermelon","Strawberry",];

join()

join() method returns a new string by concatenating all of the elements of an array, separated by a comma or by the specified separator.

Syntax:

arrayName.join(seprator)

seprator(optional) :- optional seprator string

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

console.log(fruits.join()); // apple,grapes,banana,orange,guava
console.log(fruits.join("-")); // apple-grapes-banana-orange-guava

includes()

includes() method is used to check whether an element is in the array or not. It returns true if the element is in the array else it returns false.

Syntax:

arrayName.includes(element)

element :- element you want to check for

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// check if grapes is in the fruits array
console.log(fruits.includes("grapes")); // o/p-> true

// check if "PineApple" in in the fruits array
console.log(fruits.includes("PineApple")); // o/p -> false

fill()

fill() method fills the array with the specified value and returns the new modified array. It modifies the original array.

Syntax:-

arrayName.fill(value,startIndex,stopIndex)

value -> value you want to fill with

startIndex(optional) -> strarting index from where you want to start filling the value. The default value for this is 0.

stopIndex(optional) -> index where you want to stop the filling.rembember stopIndex is always exclusive. the default value for this is the length of the array.

let fruits = ["apple", "grapes", "banana", "orange", "guava"];

// fill "PineApple" from index 1 to index 3
let returnedArray = fruits.fill("PineApple", 1, 4);
console.log(returnedArray); // [ 'apple', 'PineApple', 'PineApple', 'PineApple', 'guava' ]
console.log(fruits); //[ 'apple', 'PineApple', 'PineApple', 'PineApple', 'guava' ]

// fill fruits array with "Watermelon"
let returnedArray2 = fruits.fill("Watermelon");
console.log(returnedArray); // ["Watermelon", "Watermelon", "Watermelon", "Watermelon", "Watermelon"];
console.log(fruits); // ["Watermelon", "Watermelon", "Watermelon", "Watermelon", "Watermelon"];

indexOf()

indexOf method returns the index of the given element, if there are duplicate elements in the array then it returns the index of elements that occur first and if the element is not present in the array then it returns -1.

Syntax:-

arrayName.indexOf(element)

let fruits = ["apple", "grapes", "banana", "orange", "guava", "apple"];
// find the index of "grapes"
console.log(fruits.indexOf("grapes")); // 1

// find the index of "apple"

// apple can be found at index 0 and at index 5, but this method only return index of element which occur first.
console.log(fruits.indexOf("apple")); // 0

// find the index of "PineApple"
console.log(fruits.indexOf("PineApple")); // -1 because "PineApple is not present in the array."

isArray()

isArray() method checks if the object is an array. We know that everything in JavaScript is an object. If the object is an array then it returns true and if not then it returns false.

Syntax:-

Array.isArray(arrayName)

let fruits = ["apple", "grapes", "banana", "orange", "guava", "apple"];

console.log(Array.isArray(fruits)); // true

keys()

The keys() method returns an Array Iterator object that contains the keys for each index in the array.

Syntax:-

arrayName.keys()

let fruits = ["apple", "grapes", "banana", "orange", "guava", "apple"];

let KeyIterator = fruits.keys();

for (let key of iterator) {
  console.log(key);
}

// output
/*
0
1
2
3
4
5
*/

values()

The values() method creates a new iterator object that allows you to access the values of each index in the array. This iterator can be used to iterate through the values of the array in a loop.

Syntax :-

arrayName.values()

let fruits = ["apple", "grapes", "banana", "orange", "guava", "apple"];

let valueIterator = fruits.values();

for (let value of valueIterator) {
  console.log(value);
}

// Output
/*
apple
grapes
banana
orange
guava
apple
*/

Not the End ๐Ÿ˜’

That's it, for now, there are many more array methods that are left to cover in this article, I will be updating this article as I learn and explore more. Write your feedback in the comment section.

Did you find this article valuable?

Support Ankit Kumar by becoming a sponsor. Any amount is appreciated!