Table of contents
Array
Introduction To Array
An array is a connecting area of memory divided into equal parts of equal length.
If we decode this above line, we can say that array is an object that can store multiple values in a single variable simultaneously. A variable is only capable of holding a single value and an extension to this is an array where one can store a collection of multiple items under a single variable name.
This is the way to declare an array
const word = ['Alok', 'World', 'Hitesh Sir', '01', 45];
Output
As given above, an array in Javascript can hold different elements such as Strings, Numbers, Numbers, and Boolean as well.
Characteristics of Array
In Javascript, arrays are a non-primitive data type or reference type but instead, it is an object that holds the following characteristics.
The arrays are resizable in Javascript and can hold multiple objects of different data types which is not possible in conventional languages.
In JavaScript array elements start at index
0
, the next one at1
, and so on. This is why Javascript's arrays are zero-indexed and the last one holds the value or length of minus1
.All standard built-in copy operations in Javascript objects created shallow copies and not deep copies. That means whenever we do operations similar to copy then, a new array is created rather than modifying the original one.
Array Type
There are 2 types of arrays in Javascript One-Dimensional Arrays and Multi-Dimensional Arrays.
One-Dimensional JavaScript Array
It is the simplest form of the array of elements where items are stored linearly and each one is specified by the index of elements stored. One-Dimensional Javascript arrays are single-row or single-column arrays. This is also known as a linear array
or 1-D array
.
Multi-Dimensional JavaScript Array
Multi-Dimensional Array is not directly mentioned in JavaScipt, unlike C/C++. In Javascript multi-dimensional array is nothing but an array inside an array. Here we need to create a multi-dimensional array with the help of a one-dimensional array. Even the declaration is the same as declaring the normal one-dimensional array.
Examples 1
//These are some 1D array
var emp1 = ["Manoj", 24, 10000];
var emp2 = ["Kishan", 30, 20000];
var emp3 = ["Raj", 28, 44000];
var emp4 = ["Josh", 31, 27000];
var emp5 = ["Hitesh", 29, 32000];
//All the 1D arrays are inside a single variable that is also a 1D array
var salary = [emp1, emp2, emp3, emp4, emp5];
There is also another way to declare a 2-D array and this method is similar to declaring an object in Javascript which is also known as array literals.
Examples 2
var salary = [
["Manoj", 24, 10000],
["Kishan", 30, 20000],
["Raj", 28, 44000],
["Josh", 31, 27000],
["Hitesh", 29, 32000],
];
Here the variable "salary" act as a multidimensional array and also know as array literals.
Method
As we are familiarized with the array and declaration, now let's discuss a few methods that can be used with the arrays to manipulate and define some better use cases with the elements.
1. length
As the name suggests, the array method length
is used to find out the total array length or number of elements in the array.
Syntax
arrayname.length
Let's consider the above image where all the days in a week are stored in a single variable, say 'weekdays'. Now, if consider using the length
method with the 'weekdays' and we get the following output.
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays.length);
Output
7
2. includes
Suppose, we have a bunch of elements in our array and we need to find out whether the specific item or element is present in that array, then the use of includes
will solve our query. The include
method returns true
if that particular element is present in the array, otherwise false
is returned.
Syntax
arrayName.includes(element_To_Be_Found);
Let's consider the above image where all the days in a week are stored in a single variable 'weekdays'. If we want to search for "Monday", we are going to get a True
value and False
in any other variable apart from the elements inside it. Let's understand the small piece of code.
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays.includes("Apple"));
console.log(weekdays.includes("Monday"));
Output
false
true
3. indexOf
The indexOf() method returns the initial index in the array at which the element has been found otherwise it returns -1
if an element cannot be found.
Syntax
indexOf(searchElement)
indexOf(searchElement, fromIndex);
Let's consider the above image where all the days in a week are stored in a single variable 'weekdays'. If we want to find the index for "Friday", we are going to get 4
and -1
if we try to find any other element that is not present in that array. Let's understand this with a small piece of code.
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays.indexOf("Friday"));
console.log(weekdays.indexOf("Apple"));
Output
4
-1
4. push
The push() method is used to add a new element or item in the last index of a predefined array. The push() method changes the total length of the array. Apart from it, the method returns the new length of the array by default.
Syntax
arrayName.push(newElement);
Let's consider the above image where all the days in a week are stored in a single variable 'weekdays'. If we want to enter a new element, let's say the month, we need to push the element according to the given syntax. The new element gets added to the end of the block and returns the new length as an output. Let's understand this with a small piece of code.
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays.push("October"));
console.log(weekdays);
Output
8
[
'Monday', 'Tuesday',
'Wednesday', 'Thursday',
'Friday', 'Saturday',
'Sunday', 'October'
]
5. pop
In simple terms, I would say that the pop() method is just the reverse of the push method. It is used to remove the last index's element of a predefined array. The pop() method by default returns the removed element as its output.
Syntax
arrayName.pop();
Consider the above image where all the days in a week are stored in a single variable 'weekdays'. If we want to remove the last element from the array then, we need to pop the element according to the given syntax. The removed element gets printed as an output. Let's understand this with a small piece of code where we first add an element using push and remove the same using the pop method.
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays.push("October"));
console.log(weekdays);
console.log(weekdays.pop(""));
Output
8
[
'Monday', 'Tuesday',
'Wednesday', 'Thursday',
'Friday', 'Saturday',
'Sunday', 'October'
]
October
6. concat
Concat() method is simply joining two or more arrays where the mentioned arrays become one. The method by default returns a new array, the joined one which we need to store in any variable. But there is one thing about the method, it doesn't change the original array and keeps it intact.
Syntax
array01.concat(array02, array03);
The above image shows the method has added the "fruit" array and the "veggie" array to make a new array that is "food". Let's understand this method with a small piece of code.
let fruit= ['Apple', 'Mango', 'Litchi', 'Jackfruit', 'Tomato'];
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
let food = fruit.concat(fruit, veggies);
console.log(food);
Output
[
'Apple', 'Mango',
'Litchi', 'Jackfruit',
'Tomato', 'Apple',
'Mango', 'Litchi',
'Jackfruit', 'Tomato',
'cauliflower', 'cabbage',
'ladyfinger', 'spinach',
'potato'
]
7. splice
The definition of splice is very simple, it adds/or removes array elements. But again the question arises, why we are using it when we have push and pop? The answer is simple, push and pop only operate in the last index or last elements of the array. What if we need to enter or remove the elements from any index of the array? This is why Splice came into the picture. Moreover, this method modifies the original array just like push and pop.
Now as we know, that splice() can add/remove elements from anywhere in the array, then it is clear to some extent that syntax might include the address/index and items list as well. Let's see the proper syntax for the splice below.
Syntax
arrayName.splice(index, howManyElement, item1, item2, ....., itemX);
In the above syntax, index
and howManyElement
always keep the student in confusing most of the time. The index
is the address from where the new elements should get inserted and howManyElement
is the number of elements that should get overwritten. Suppose, if you just want to add the element and not going to delete any elements then the howManyElement
should be 0
.
Image - 1
Image - 2
Consider the above images where the splice has been used differently. In image - 1, splice() has been used without removing any pre-defined elements. In image -2, the splice() is used not only to insert the element but also to overwrite and remove it from the array list. Let's understand this with a small piece of code.
Example 01
let fruit= ['Apple', 'Mango', 'Litchi', 'Jackfruit', 'Tomato'];
fruit.splice(2, 0, 'Lemon', 'Kiwi');
console.log(fruit);
Output
[ 'Apple', 'Mango', 'Lemon', 'Kiwi', 'Litchi', 'Jackfruit', 'Tomato' ]
Example 02
let fruit= ['Apple', 'Mango', 'Litchi', 'Jackfruit', 'Tomato'];
fruit.splice(2, 2, 'Lemon', 'Kiwi');
console.log(fruit);
Output
[ 'Apple', 'Mango', 'Lemon', 'Kiwi', 'Tomato' ]
8. slice
Just as its name slice is being used to slice up a part of a pre-defined array as a new array. A new array is being returned that has been chopped up from the existing array. The interesting thing to notice here is that the slice() doesn't change the original array. The syntax used the starting index and the ending index(non-inclusive) of the array. The start and end indexes sometimes also be using negative values.
Syntax
array.slice(start, end);
The above image shows the method has extracted a new array from the fruit
and the third index was non-inclusive. Let's understand this method with a small piece of code.
let fruit= ['Apple', 'Mango', 'Litchi', 'Jackfruit', 'Tomato'];
let newFruit = fruit.slice(1, 3);
console.log(newFruit);
Output
[ 'Mango', 'Litchi' ]
9. sort
The sort method in Javascript is used to sort the elements as strings in ascending and alphabetical order. The thing to notice here is that it overwrites the original array while sorting the elements.
Syntax
array.sort();
The above image shows the method has sorted the array in alphabetical order. Let's understand this method with a small piece of code.
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
console.log(veggies.sort());
Output
[ 'cabbage', 'cauliflower', 'ladyfinger', 'potato', 'spinach' ]
10. reverse
As the name suggests, the reverse() method is used to reverse the order of elements in the given array. The reverse() method overwrites the original array.
Syntax
array.reverse()
The above image shows the method has reversed the array's order. Let's understand this method with a small piece of code.
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
console.log(veggies.reverse());
Output
[ 'potato', 'spinach', 'ladyfinger', 'cabbage', 'cauliflower' ]
11. shift
The shift method removes the first item of the given array and shifts its index. The shift() method changes the original array and returns the shifted elements. The index value of 0
is shifted to the next element after removing the first element. The default output would be the elements that have been removed.
Syntax
array.shift()
The above image shows the method has removed the first item and re-arranged the array's order. Let's understand this method with a small piece of code.
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
console.log(veggies.shift());
Output
cauliflower
12. unshift
The unshift() method is just the opposite of the shift() method. When shift() removes the first elements and shifts the 0
index to the next one, unshift() does just the opposite of it. The unshift() adds the new element to the 0
index and shifts the elements accordingly. This method also overwrites the original array and returns the new length.
Syntax
array.unshift(element1, element2, element3 .... elementX);
In the above image, the method has the first item and re-arranged the array's order. Let's understand this method with a small piece of code.
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
console.log(veggies.unshift('broccoli', 'Greenpeas'));
Output
7
[
'broccoli',
'Greenpeas',
'cauliflower',
'cabbage',
'ladyfinger',
'spinach',
'potato'
]
13. includes
The best way to find whether an element is present in an array is the include
method. The method returns true
if the array contains a specified value otherwise returns false
if the element is not found. The only thing to notice here is that the include
method is case-sensitive.
Syntax
array.includes(element, start);
In the above image, the element that needs to be searched is potato
and the search starts from index 1
. As soon as the element is found after index 1, true
is returned. Let's go in-depth with the piece of code.
let veggies= ['cauliflower', 'cabbage', 'ladyfinger', 'spinach', 'potato'];
console.log(veggies.includes('potato', '1'));
Output
true
14. find
The find() method in Javascript is used to find the value of the first element that is going to satisfy a particular condition(test function) in the array. The method checks all the elements of the array and as soon as it finds the elements that are going to satisfy the condition is going to print. The method doesn't work on an empty array and will not modify the original array.
Parameters: This method accepts 5 parameters as mentioned above and described below:
function: It is the function of the array that works on each element.
currentValue: This parameter holds the current element.
index: It is an optional parameter that holds the index of the current element.
arr: It is an optional parameter that holds the array object to which the current element belongs.
thisValue: This parameter is optional. If a value is to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value.
Syntax
array.find(function(currentValue, index, arr),thisValue);
In the above image, the condition is to find an element that is greater than 20. So whatever number comes first greater than 20 is going to be the output. In our case, it is 30. Let's go in-depth with the piece of code.
let array = [10, 20, 30, 40, 50];
let found = array.find(function (element) {
return element > 20;
});
console.log(found);
Output
30
15. filter
The filter method creates a shallow copy of a segment of a given array that is filtered down by implementing a particular function. Unlike the find() function, this method returns a new array with all the elements that pass the test in a testing function. Similar to find(), it also doesn't operate on empty elements and doesn't change the original array. Its syntax includes a test function that has some specific condition for each array element, the value of the current element, an optional index value of the current element, and the array of the current element. If no element of the array pass the test then it is going to return an empty array.
Syntax
array.filter(function(currentValue, index, arr), thisValue)
In the above image, the condition is to find an element that is greater than 20. So whatever number greater than 20 is going to be returned as an array. Let's go in-depth with the piece of code.
let array = [10, 20, 30, 40, 50];
let found = array.filter(function (element) {
return element > 20;
});
console.log(found);
Output
[ 30, 40, 50 ]
16. toString
The toString() method is used to convert an array into a string and return the result. The method returns a string with array values that is separated by commas. The method doesn't change the original string.
Syntax
string.toString()
Note: The toString() method is also present with every object of Javascript that is used internally by Javascript when an object needs to be displayed as text and needs to be used as a string. Moreover, it used parameters such as base - 2, and base-16 to convert the numeric value as per the requirement.
In the above image, the array is converted into a string.
let array = [10, 20, 30, 40, 50];
console.log(array.toString());
Output
10,20,30,40,50
17. every
The every() method examines all the array's elements and then checks whether all the elements of the particular array pass the given condition. The every() method executes a function for each array element and returns true
if the function is true for all elements. If the condition for one element goes wrong or fails, then it returns false
. This method doesn't get executed for empty elements and doesn't change the original array.
This method accepts five parameters as mentioned above and described below:
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
array: This parameter is optional, it holds the complete array on which Array.every is called.
thisArg: This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Syntax
array.every(function(currentValue, index, arr), thisValue)
In the above image, the condition is to check whether the given arrays are positive or greater than 0
. In the first array, everything was positive therefore the output was True
. In the second array, 2 elements were negative and that is why the output was false
. Let's go in-depth with the piece of code.
function ispositive(element) {
return element > 0;
}
let arr1 = [10, 20, 30, 40, 50];
let arr2 = [-10, 20, 30, -40, 50];
let result1 = arr1.every(ispositive);
console.log(result1);
let result2 = arr2.every(ispositive);
console.log(result2);
Output
true
false
18. map
The map() method creates a new array from the results that are coming from a function iterating over each element of an array. The function could be anything such as the square root of given arrays, concatenation of the elements, and many more. Here let's take the example of the squaring of numbers.
Syntax
array.map(function(currentValue, index, arr), thisValue)
In the above image, the condition or the function is to find a square for each element of the array. Let's go in-depth with the piece of code.
let num = [5, 20, 8, 6, 11];
let result = num.map(function square(element) {
return element*element;
}
)
console.log(result);
Output
[ 25, 400, 64, 36, 121 ]
19. reduce
The reduce() is used to minimize the values of an array to a single value through a reducer function for the array element. The reducer function provides the accumulated result, mostly from left to right. This method doesn't work for empty array elements. Moreover, it doesn't change the original array.
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue);
In the above image, the condition or the function is to find a sum for each element of the array. Let's go in-depth with the piece of code.
let num = [5, 20, 8, 6, 11];
function sum(total, number){
return total + number;
}
let result = num.reduce(sum, 0);
console.log(result);
Output
50
Conclusion
So, here is the most frequently used and important methods of arrays used in Javascript. These concepts are often asked in the interviews and have day-to-day usage if you are a beginner as well as an expert coder. Hope you find this article useful and knowledgeable. If you want to read in-depth about the array methods or research on that, I would suggest MDN Doc.