JavaScript Array. Everything You Need To Know
Posted by TotalDC
Let’s continue our JavaScript series and learn how to create and manipulate JavaScript array.
What Is An Array
Simply saying – array is a variable that allows you to store more than one value while using single variable name. JavaScript arrays can store any value – string, number, object, function and other arrays. So you can make complex data structures such as an array of objects or an array of arrays.
Let’s say you want to store some data in your JavaScript code. Here is an example:
let color1 = "Red";
let color2 = "Green";
let color3 = "Blue";
This method is good if you have just a couple of data that you want to put into an array. But usually there will be more data than that so it is quite hard and boring to store each of them in a separate variable. You can solve this problem with array. Array provides an ordered structure for storing multiple values or a group of values.
How To Create An Array In JavaScript
The simplest way to create an array in JavaScript is simply enclosing a comma separated list of values in square brackets []. Here is an example:
let myArray = [element0, element1, ..., elementN];
Also you can do that by using the Array() constructor, just like that:
let myArray = new Array(element0, element1, ..., elementN);
How To Access The Array Elements
Array elements can be accessed by their index using the square bracket notation. An Index is a number that represents element’s position in the array.
Just like in other programming languages like for example PHP, array indexes are zero-based. This means that the first item of an array is stored at index 0, not 1, the second item is stored at index 1 etc. Array indexes start at 0 and got up to the number of elements minus 1. So, array of five elements would have indexes from 0 to 4.
Here is an example of how you can get individual array elements by their index:
let fruit = ["Apple", "Banana", "Mango", "Orange", "Kiwi"];
console.log(fruit[0]); // Result: Apple
console.log(fruit[1]); // Result: Banana
console.log(fruit[2]); // Result: Mango
console.log(fruit[fruit.length - 1]); // Result: Kiwi
How To Find Length Of An Array
The length property returns the length of an array, which is the total number of elements in that array. Array length is always greater that the index of any of its elements.
let fruit = ["Apple", "Banana", "Mango", "Orange", "Kiwi"];
console.log(fruit.length); // Result: 5
How To Loop Through Array Elements In JavaScript
To access each element of an array in sequential order you can use for loop. Just like that:
let fruit = ["Apple", "Banana", "Mango", "Orange", "Kiwi"];
// Iterates over array elements
for(var i = 0; i < fruit.length; i++) {
console.log(fruit[i] + "<br>");
}
ECMAScript 6 introduced even simpler way to iterate over array elements by using for-of loop. In this loop you do not have to initialize and keep track of the loop counter variable. Here is an example:
let fruit = ["Apple", "Banana", "Mango", "Orange", "Kiwi"];
// Iterates over array elements
for(var item of fruit) {
console.log(item + "<br>");
}
Also you can iterate over the array elements by using for-in loop. Just like that:
let fruit = ["Apple", "Banana", "Mango", "Orange", "Kiwi"];
// Loop through all the elements in the array
for(var i in fruit) {
console.log(fruit[i] + "<br>");
}
Just so you know, the for-in loop should not be used to iterate over an array if index order is important. The for-in loop is optimized for iterating over object’s properties. It is better to use for loop with a numeric index or for-of loop.
How To Add New Elements To An Array In JavaScript
If you want to add new element at the end of an array, you simply use the push() method. Just like this:
let colors = ["Red", "Green", "Blue"];
colors.push("Yellow");
console.log(colors); // Result: Red,Green,Blue,Yellow
console.log(colors.length); // Result: 4
What if you want or need to add new element at the beginning of an array? Then you will use the unshift() method. Like this:
let colors = ["Red", "Green", "Blue"];
colors.unshift("Yellow");
console.log(colors); // Result: Yellow,Red,Green,Blue
console.log(colors.length); // Result: 4
Also worth noticing that you don’t need to keep adding new elements one at the time. You can add multiple elements at once with both push() and unshift() methods. Just like in the example:
let colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Purple");
colors.unshift("Yellow", "Grey");
console.log(colors); // result: Yellow,Grey,Red,Green,Blue,Pink,Purple
console.log(colors.length); // Result: 7
How To Remove Elements From An Array In Javascript
If you want to remove the last element from an array you need to use pop() method. This method returns the value that was popped out. Here’s an example:
let colors = ["Red", "Green", "Blue"];
let last = colors.pop();
console.log(last); // Result: Blue
console.log(colors.length); // Result: 2
Also you can remove the first element from an array. For that you need to use shift() method. This method returns the value that was shifted out. Here’s an example:
let colors = ["Red", "Green", "Blue"];
let first = colors.shift();
console.log(first); // Result: Red
console.log(colors.length); // Result: 2
How To Add Or Remove Elemenets From Anywhere In Array
For this you need splice() method. This method allows you to add or remove elements from any index. Sintax of splice() method looks like this – arr.splice(startIndex, deleteCount, elem1, …, elemN).
This method takes three parameters – the first parameter is the index at which to start splicing the array, it is required. The second parameter – number of elements to remove (use 0 if you don’t want to remove any elements), this parameter is optional. And the third parameter – set of replacement elements. This parameter also is optional. Here is an example of this method:
let colors = ["Red", "Green", "Blue"];
let removed = colors.splice(0,1); // Remove the first element
console.log(colors); // Result: Green,Blue
console.log(removed); // Result: Red (one item array)
console.log(removed.length); // Result: 1
removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at position one
console.log(colors); // Result: Green,Pink,Yellow,Blue
console.log(removed); // Empty array
console.log(removed.length); // Result: 0
removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values, remove one
console.log(colors); // Result: Green,Purple,Voilet,Yellow,Blue
console.log(removed); // Result: Pink (one item array)
console.log(removed.length); // Result: 1
This splice() method returns an array of deleted elements or an empty array if no elements were deleted. If the second argument is omitted all elements from the start to the end of the array are removed. Unlike slice() and concat() methods, splice() method modifies the array on which it is called.
How To Create A String From An Array
What if you want or need to create string form array elements? To do this you need to use the join() method. This method takes optional parameter which is a separator string that is added in between each element. If you omit the separator JavaScript will use comma by default. The following example shows hot it works:
let colors = ["Red", "Green", "Blue"];
console.log(colors.join()); // Result: Red,Green,Blue
console.log(colors.join("")); // Result: RedGreenBlue
console.log(colors.join("-")); // Result: Red-Green-Blue
console.log(colors.join(", ")); // Result: Red, Green, Blue
To achieve same result you can use toString() method. This method does not accept the separator parameter like join(), it creates comma separated string every time. Here’s an example:
let colors = ["Red", "Green", "Blue"];
console.log(colors.toString()); // Result: Red,Green,Blue
How To Extract A Portion Of An Array
Let’s say you want to extract a portion of an array, but keep the original array intact. To do this you can use the slice() method. This method takes 2 parameters – start index and an optional end index arr.slice(startIndex, endIndex). Let’s look at the example:
let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
let subarr = fruits.slice(1, 3);
console.log(subarr); // Result: Banana,Mango
If endIndex parameter is omitted then all elements to the end of the array are extracted. You can specify negative indexes or offsets and then slice() method will extract elements from the end of an array rather then the beginning. Here’s how it looks:
let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
console.log(fruits.slice(2)); // Result: Mango,Orange,Papaya
console.log(fruits.slice(-2)); // Result: Orange,Papaya
console.log(fruits.slice(2, -1)); // Result: Mango,Orange
How To Merge Two Or More Arrays
The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays but returns new one. Here’s an example:
let pets = ["Cat", "Dog", "Parrot"];
let zoo = ["Tiger", "Wolf", "Zebra"];
// Creating new array by combining pets and zoo arrays
let animals = pets.concat(zoo);
console.log(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra
The concat() method can take any number of arrays. Here’s how it looks:
let pets = ["Cat", "Dog", "Parrot"];
let zoo = ["Tiger", "Wolf", "Zebra"];
let bugs = ["Ant", "Bee"];
// Creating new array by combining pets, wilds and bugs arrays
let animals = pets.concat(zoo, bugs);
console.log(animals); // Result: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee
How To Search Through An Array
If you want to search an array for a specific value, you can simply use the indexOf() and lastIndexOf() methods. If the value is found, both methods return an index of that array element. If the value is not found you will get -1 as result. The indexOf() method returns the first one found and the lastIndexOf() as you may guess returns the last one found.
let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
console.log(fruits.indexOf("Apple")); // Result: 0
console.log(fruits.indexOf("Banana")); // Result: 1
console.log(fruits.indexOf("Pineapple")); // Result: -1
Both methods accept an optional integer parameter from which specifies the index from where to start the search. Example looks like this:
let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
// Searching forwards, starting at from- index
console.log(arr.indexOf(1, 2)); // Result: 3
// Searching backwards, starting at from index
console.log(arr.lastIndexOf(1, 2)); // Result: 0
Meanwhile includes() method is used when you need to find out whether an array includes a certain element or not. This method takes the same parameters as indexOf() and lastIndexOf() but returns true or false. Here is an example for you:
let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
console.log(arr.includes(1)); // Result: true
console.log(arr.includes(6)); // Result: false
console.log(arr.includes(1, 2)); // Result: true
console.log(arr.includes(3, 4)); // Result: false
If you want to search an array based on certain condition then you need to use find() method. This method returns the value of the first element in the array that meets the condition. If no such elements found you will get undefined as a result.
let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
let result = arr.find(function(element) {
return element > 4;
});
console.log(result); // Result: 5
Also you can use findIndex() method. This method returns the index of an element if it finds any. Let’s look at the example:
let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
let result = arr.findIndex(function(element) {
return element > 6;
});
console.log(result); // Result: 8
The find() method looks only for the first element that meets the condition. If you need to find all the elements you can use filer() method.
This filter() method creates new array with all the elements that were found. Here’s how it looks:
let arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
let result = arr.filter(function(element) {
return element > 4;
});
console.log(result); // Result: 5,7
console.log(result.length); // Result: 2
Leave a Reply