What exactly are “arrays”? And how array methods in javascript are used?
Arrays are one of the data structures in many programming languages that stores multiple values of any kind of data type in them as in a single variable. An array in JavaScript is represented in square brackets [ ], in which the elements are separated by a comma ( , ). As a result, strings, Booleans, objects, literals, and other arrays can all be embedded in a single array.
For example,
const mixedArray = ['John', 65, true, {}]
From the above example, we observe that the array ‘mixedArray’ consists of String (John), numerals (65), Boolean (true), and object {}. Arrays in Javascript are mutable, so we can add, delete, and modify the already defined array.
The built-in array methods are used to perform various array operations like concat, reverse, slice, find, push, pop, etc. The use of these methods makes tasks easier to perform and faster.
Let’s take a look at the array methods in JavaScript with some examples in this tutorial.
Array Methods
Add or remove elements from an array using these methods
Javascript consists of numerous array methods which are used for adding and removing elements from the array. A few ways for adding and removing operations are listed below.
push()
push () in JS is used to add any number of elements at the end of the array and returns a new array with the newly added elements at its end.
const fruites = ['apple', 'banana']
console.log(fruites);
// Output: ['apple', 'banana']
fruites.push('cherry')
console.log(fruites);
// Output: ['apple', 'banana', 'cherry']
unshift ()
Well, push() is used to add elements at the end of the array, and if you want to add elements at the beginning of the array, then the unshift() method is used. unshift () adds elements to the array from the beginning and results in a new array of added elements.
const fruites = ['apple', 'banana']
console.log(fruites);
// Output: ['apple', 'banana']
fruites.unshift('cherry')
console.log(fruites);
// Output: ['cherry', 'apple', 'banana']
pop ()
pop() is used to remove a single element from the array from its end. So, whenever we use a pop () method, an element from the end of the array is removed and a new array is formed.
const fruites = ['apple', 'banana', 'cherry']
fruites.pop();
console.log(fruites);
// Output: ['apple', 'banana']
shift ()
To extract/remove an element from the beginning of an array we use shift().
[Also Read, JavaScript Coding Interview Questions and Answers]
const fruites = ['apple', 'banana', 'cherry']
fruites.shift();
console.log(fruites);
// Output: ['banana', 'cherry']
splice()
splice() is used for multipurpose operations such as inserting and deleting array elements.
The syntax of the splice () follows:
Syntax: arr.splice(start[, delete count, ele1, ele2,…, eleN)
Let us look at an example where splice() operates as an insert of elements into the array.
const nums = [1, 2, 5, 6, 8]
console.log(nums);
// Output: [1, 2, 5, 6, 8]
nums.splice(2, 0, 3, 4);
console.log(nums);
// Output: [1, 2, 3, 4, 5, 6, 8]
Splice can insert elements without removing any elements from the array only if the delete count is zero. From the above example, the delete count is zero, and the new elements ‘3’ and ‘4’ are added to the array at an index of 2.
const nums = [1, 2, 5, 6, 8]
console.log(nums);
// Output: [1, 2, 5, 6, 8]
nums.splice(1, 1);
console.log(nums);
// Output: [1, 5, 6, 8]
nums.splice(0, 2, 10, 11, 12);
console.log(nums);
// Output: [10, 11, 12, 6, 8]
We can delete a single specified element using its index, or we can delete a group of elements together using splice(). In the example, we noticed that with the use of splice () we can delete a single element or multiple elements from the array, and also we can perform inserting and deleting operations on arrays using splice.
concat()
Concatenation in arrays is a process of merging one or more arrays into a single new array without disturbing the existing array.
const str1 = 'Hello'
const str2 = 'Everyone'
const msg = str1.concat(' ', str2);
console.log(msg)
// Output: Hello Everyone
const word = 'Hello, ';
const greeting = word.concat('Naveen', ' How are you?')
console.log(greeting);
// Output: Hello, Naveen How are you?
const a1 = ['a', 'b', 'c'];
const a2 = ['d', 'e', 'f'];
const mergeArrays = a1.concat(a2);
console.log(mergeArrays);
// Output: ['a', 'b', 'c', 'd', 'e', 'f']
forEach ()
For each array element, the forEcah() method will be used to call a function. The forEach () method is not applicable for an empty array of elements.
Syntax: array.forEach(function(currentValue, index, arr), thisValue)
const array = ['a', 'b', 'c', 'd'];
array.forEach(function(elem){
console.log(elem)
});
// Output: a, b, c, d
const nums = [10, 20, 30, 40]
function calcTotal(args) {
var total = 0;
args.forEach(arg => {
total += arg;
});
console.log(total);
}
calcTotal(nums);
// Output: 100
In the above example, the method forEach() calls a function for every element in the array and prints the result as ‘100’ for the function ‘calcTotal’.
Searching for elements in an array
In javascript, there are a few built-in array methods that are used for searching elements in the array. Here is the list of the array methods that are used for searching an element in the array.
indexOf ():
Syntax: arr.indexOf(element, from)
Using the indexOf() method, we can find the index position of the element in the array. The indexOf() method starts searching for the element right from the beginning of the array and returns the index value of the element if found. Otherwise, it will give ‘-1’ as an output, which indicates the absence of the element.
let array = [1, 10, true, 'john']
console.log(array.indexOf('john')) // 3
console.log(array.indexOf(1)) // 0
console.log(array.indexOf(true)) // 2
console.log(array.indexOf('ramu')) // -1
lastIndexOf ()
Syntax: arr.lastIndexOf(element, from)
The lastIndexOf () method performs the same function as the indexOf () method, but it searches for the element from right to left in the array.
let array = ['html', 'css', 'js']
console.log(array.lastIndexOf('html')) // 0
console.log(array.lastIndexOf('css')) // 1
console.log(array.lastIndexOf('js')) // 2
console.log(array.lastIndexOf('angular')) // -1
includes ():
Syntax: arr.includes(element, from)
The method includes() searches for the element in the array and returns “true” if found.
let nums = [1, 10, 100, 1000]
console.log(nums.includes(1000)) // true
console.log(nums.includes(20)) // false
map()
The method map() produces a new array and returns the result of the specified function that runs on every element in the array.
let nums = [1, 10, 20, 30, 40]
const mapped = nums.map(function(elem) {
return elem + 10
})
console.log(mapped); // [11, 20, 30, 40, 50]
find ()
The useful way of finding an element presence in an array is done through the find () method.
Syntax: arr.find (function)
It returns the element and stops the function iteration if the element is found. Else it results as undefined.
let people = [
{id: 1, name: 'john'},
{id: 2, name: 'smith'},
]
const person = people.find(function(elem) {
return elem.id == 2
})
console.log(person.name); // smith
findIndex ()
findIndex() method is similar to the find() method where it returns the index values of the elements if the element is found, else it results in ‘-1’ if the element is absent.
let people = [
{id: 1, name: 'john'},
{id: 2, name: 'smith'},
]
const person = people.findIndex(function(elem) {
return elem.name === 'smith'
})
console.log(person); // 1
reverse()
To reverse the arrangement of an array, use the reverse () method. It reverses the array order and returns the new reversed array that consists of the last element as the first element and the first element as the last element in the newly formed array.
const nums = [1, 2, 3, 4, 5];
console.log(nums);
// Output: [1, 2, 3, 4, 5]
nums.reverse();
console.log(nums);
// Output: [5, 4, 3, 2, 1]
filter ()
The method filter() creates a new array containing only elements that satisfy the given condition in the function. filter() method is similar to the find() method, but the find method is used to find one element in the array, whereas the filter method is used to find the group of elements present in the array. If it finds the elements, then it returns the elements and stops iteration, else it returns an empty array.
const students = [
{id:1, name: 'Naveen', age: 17, gender: 'M'},
{id:2, name: 'Vinod', age: 25, gender: 'M'},
{id:3, name: 'Shalini', age: 22, gender: 'F'},
{id:4, name: 'Geetha', age: 18, gender: 'F'}
]
const filterAge = students.filter((student) => {
return student.age < 20
})
console.log(filterAge);
// Output:
// 0: {id: 1, name: 'Naveen', age: 17, gender: 'M'}
// 1: {id: 4, name: 'Geetha', age: 18, gender: 'F'}
sort()
The sort () method usually converts the array of elements into strings and performs the comparison. The sort () method performs well for strings of alphabets or words because it converts elements to strings and compares them using UTF-16 code unit values. But in the case of the numerals, the sort () method needs some kind of modification for both ascending and descending order arrangements.
Let’s take a couple of examples to help you understand.
const nums = [5, 3, 4, 2, 1, 10];
// Ascending order
nums.sort(function(a, b) {
return a - b;
});
console.log(nums); // [1, 2, 3, 4, 5, 10]
// Descending Order
nums.sort(function(a, b) {
return b - a;
});
console.log(nums); // [10, 5, 4, 3, 2, 1]
const students = [
{id:1, name: 'Naveen', age: 17, gender: 'M'},
{id:2, name: 'Vinod', age: 25, gender: 'M'},
{id:3, name: 'Shalini', age: 22, gender: 'F'},
{id:4, name: 'Geetha', age: 18, gender: 'F'}
]
students.sort(function(a, b){
return a.age - b.age;
})
console.log(students);
// output:
// 0: {id: 1, name: 'Naveen', age: 17, gender: 'M'}
// 1: {id: 4, name: 'Geetha', age: 18, gender: 'F'}
// 2: {id: 3, name: 'Shalini', age: 22, gender: 'F'}
// 3: {id: 2, name: 'Vinod', age: 25, gender: 'M'}
From the example, we have seen that for ascending order considering a code of function as (a-b) for a and b arguments. And similarly, for the descending order, we will consider (b-a) for the a and b arguments.
split ()
split() is used to split up a string into individual strings (elements) in an array. The new array of substrings of words is formed when there is a space as a separator in the original string. The method split () won’t affect the original string and returns a new array of strings.
const empName = 'Naveen';
console.log(empName.split('')) //['N', 'a', 'v', 'e', 'e', 'n']
fill()
In the fill method, the array of the elements can be changed to a single static value, which we provide as the argument in the method. It changes the entire original array and forms a new array with a length of the original array containing the same elements and values that we pass as the argument in the method. We can also set where and which elements in the original array need to be modified with new elements by passing starting and ending indexes in the method.
The syntax is: arr.fill(element, starting_index, ending_index)
const colors = ['blue', 'red', 'orange']
colors.fill('green')
console.log(colors); // ['green', 'green', 'green']
const colors2 = ['blue', 'red', 'green'];
colors2.fill('orange', 1, 3)
console.log(colors2); // ['blue', 'orange', 'orange']
reduce()
This method reduces an array to a single value by applying a function to an accumulator and each item in the array.
When a function is invoked, the previous function’s result is sent as its first argument to the next.
As a result, the first parameter is effectively an accumulator that holds the sum of all prior executions. Finally, it becomes the outcome of reducing the entire array.
Syntax: arr.reduce(function(accumulator, item, index, array)).
Every element in the array is applied to the function one by one, and the result is “carried on” to the next call.
const nums = [1, 10, 20, 30, 40];
let total = nums.reduce(function(sum, current){
return sum + current
},0)
console.log(total);
join()
join() method does the reverse function of split() method. join() method results in a string from the array where a comma (,) is used as the default separator.
const colors = ['blue', 'red', 'orange']
const joinedText = colors.join();
console.log(joinedText); // blue,red,orange
every()
every() method checks whether every element in the array obeys/ satisfies the condition provided in the function. It evaluates to true as a result if the criteria are fulfilled.
const nums = [10, 20, 30, 40];
const greater9 = nums.every(function(number){
return number > 9
})
console.log(greater9); // true
const less10 = nums.every(function(number){
return number < 10
})
console.log(less10); // false
some()
If every() method checks the condition satisfaction of every element in the array, then some() methods check for the condition satisfaction at least by one element. So if at least one element in the array satisfies the condition, then it returns true as an output.
const nums = [10, 20, 30, 40];
const greater9 = nums.some(function(number){
return number > 30
})
console.log(greater9); // true
const less10 = nums.some(function(number){
return number < 10
})
console.log(less10); // false
slice()
slice () method is used to create a new array of selected elements in the existing original array. It creates a new array of elements by the use of start and end indexes provided as arguments in the method.
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)
console.log(fruits); // ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
console.log(citrus); // ['Orange', 'Lemon']
Array.isArray()
If an object is an array, the isArray() method returns true; otherwise, it returns false. The syntax of isArray() method is “Array.isArray(obj)”; the use of Array.isArray() is essential and results in an “undefined” as output if any other array is used in place of “Array” in Array.isArray().
console.log(Array.isArray(['blue', 'red', 'orange'])); // true
console.log(Array.isArray({id: 1})) // false
console.log(Array.isArray(123)) // false
length
In JS, the length is used to return the length of an array or set the length of the array.
The syntax for setting the length of the array is “array.length = number”
The syntax for estimating the length of an array is “array.length”.
const colors = ['blue', 'red', 'orange'];
console.log(colors.length); // 3
Array.from()
From any array/ object with a length attribute, the Array.from() function returns an array. And it also returns an array from any iterable object.
The syntax is, “Array.from(object, mapFunction, thisValue)”.
let text = 'Random Text';
console.log(Array.from(text))
Output: ['R', 'a', 'n', 'd', 'o', 'm', ' ', 'T', 'e', 'x', 't']
let nums = [1, 2, 3, 4, 5];
function addNum(){
return Array.from(...arguments, function(x){
return x + 2
})
}
console.log(addNum(nums))
Output: [3, 4, 5, 6, 7]
Array.of()
The Array.of() method generates a new Array instance from a configurable number of parameters, independent of their number or argument type. The only difference between an Array() and Array.of() is, that Array.of() creates an array of a single element provided as an argument/ object in the method, whereas the Array() creates an empty array of the specified number of vacant spaces in the array.
console.log(Array.of(1)) // [1]
console.log(Array.of(1, 2, 3, 4)) // [1, 2, 3, 4]
console.log(Array.of(true)) // [true]
console.log(Array(5)) // (5) [empty × 5]
at()
The at() method accepts an integer value and returns the element at that index, which can be positive or negative. Negative integers count backwards from the array’s last element.
const arr1 = [10, 12, 14, 654, 19];
console.log(arr1.at(2)) // 14
console.log(arr1.at(-2)) // 654