5 Array Method
5 Array Method
Array properties
length property
Summary: in this tutorial, you’ll learn about the JavaScript Array length property and how to
handle it correctly.
The value of the length is 232. It means that an array can hold up to 4294967296 (232) elements.
The length property behaves differently depending on the array types including dense and sparse.
1) Dense arrays
A dense array is an array where its elements have contiguous indexes starting at zero.
For dense arrays, you can use the length property to get the number of elements in the array.
For example:
In this example, the length property returns three, which is the same as the number of elements in
the colors array.
colors.push('yellow');
console.log(colors.length); // 4
colors = [];
console.log(colors.length); // 0
fi
2) Sparse arrays
A sparse array is an array whose elements don’t have contiguous indexes starting at zero.
For example, the [10,, 20, 30] is a sparse array because the indexes of its elements are 0, 2, and 3.
In a sparse array, the length property doesn’t indicate the actual number of elements. It’s a number
that is greater than the highest index. For example:
In this example, the number of elements in the numbers array is three: 10, 20, and 30. The highest
index is three. Therefore, the length property returns four.
The following adds an element to the numbers array at the index 10:
numbers[10] = 100;
console.log(numbers.length); // 11
1) Empty an array
If you set length to zero, the array will be empty:
console.log(fruits); // []
2) Remove elements
If you set the length property of an array to a value that is lower than the highest index, all the
elements whose index is greater than or equal to the new length are removed.
The following example changes the length property of the fruits array to two, which removes
the third element from the array:
Summary
• The length property of an array is an unsigned, 32-bit integer that is always numerically
greater than the highest index of the array.
• The length returns the number of elements that a dense array has.
• For the spare array, the length doesn’t re ect the number of actual elements in the array.
• Modifying the length property can remove elements from the array or make the array spare.
fl
Section 2. Adding / removing elements
push()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array push() method to add
one or more elements to the end of an array.
push(newElement);
push(newElement1,newElement2);
push(newElement1,newElement2,...,newElementN);
The push() method returns the new value of the length property of the array object on which
you call the method.
console.log(length);
console.log(numbers);
Output:
4
[ 10, 20, 30, 40 ]
How it works.
First, de ne the numbers array that has three numbers:
Second, add the number 40 to the end of the numbers array using the push() method and assign the
return value to the length variable:
console.log(length);
console.log(numbers);
2) Using the array push() to add multiple elements to the end of an array
The following example shows how to use the push() method to add multiple elements to the
end of an array:
console.log(length);
console.log(numbers);
Output:
5
[ 10, 20, 30, 40, 50 ]
And you want to append the elements of the cmyk to the colors array.
To do that, you may use a for...of loop that iterates over the elements of the cmyk array and
use the push() method to append each element to the colors array like this:
console.log(colors);
Output:
Starting from ES6, you can use the spread operator (...) to spread the elements of the cmyk array
and push them to the colors array at the same time like this:
colors.push(...cmyk);
console.log(colors);
Using JavaScript Array push() method with array-like objects
The Array.prototype.push() method is designed to be generic on purpose. Therefore, you can call
the push() method with the call() or apply() on the array-like objects.
Under the hood, the push() method uses the length property to determine the position for inserting
the elements. If the push() method cannot convert the length property into a number, it’ll use 0 as
the value for the index.
let greetings = {
0: 'Hi',
1: 'Hello',
length: 2,
append(message) {
[].push.call(this, message);
},
};
greetings.append('Howdy');
greetings.append('Bonjour');
console.log(greetings);
Output:
{
'0': 'Hi',
'1': 'Hello',
'2': 'Howdy',
'3': 'Bonjour',
length: 4,
add: [Function: add]
}
How it works.
First, de ne the greetings object that has three properties 1, 2, and length and one method append():
let greetings = {
0: 'Hi',
1: 'Hello',
length: 2,
append(message) {
[].push.call(this, message);
},
};
fi
The append() method calls the push() method of an array object to append the message to
the greetings object.
Second, call append() method of the greetings object:
greetings.append('Howdy');
greetings.append('Bonjour');
In each call, the push() uses the length property of the greetings object to determine the position
where it appends the new element and increases the length property by one.
As a result, the greetings object has two more elements at the index 2 and 3. And
the length property is 4 after the calls.
console.log(greetings);
To allow the append() method to accepts a number of messages, you can modify the method like this:
let greetings = {
0: 'Hi',
1: 'Hello',
length: 2,
append() {
[].push.call(this, ...arguments);
},
};
greetings.append('Howdy', 'Bonjour');
console.log(greetings);
How it works.
First, remove the message parameter from the append method.
Second, spread out the elements of the arguments object and push them to the greetings object.
Summary
• Use the JavaScript array push() method to append one or more elements to an array.
• The push() method also works with an array-like object.
unshift()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array unshift() method to add one
or more elements to the beginning of an array.
unshift(element);
unshift(element1, element2);
unshift(element1, element2,...elementN);
Because the unshift() method needs to reindex the existing elements, it is slow if the array
has many elements.
Note that to add one or more elements to the end of an array, you can use the push() method
instead.
Output:
{ length: 3 }
{ numbers: [ 20, 30, 40 ] }
How it works.
First, de ne an array that has two elements:
2) Using the JavaScript Array unshift() method to prepend multiple elements to an array
The following example uses the unshift() method to add two elements at the beginning of an array:
Output:
{ length: 4 }
{ numbers: [ 10, 20, 30, 40 ] }
fi
3) Using the JavaScript array unshift() to add elements of an array to another array
The following example uses the unshift() method to add elements of an array to the
beginning of another array:
console.log(days);
Output:
Starting from ES6, you can use the spread operator to make the code more concise, like this:
days.unshift(...weekends);
console.log(days);
Using the JavaScript Array unshift() method with array-like objects
The unshift() method is generic. Therefore, it can work well with array-like objects. To call
the unshift() method from an array-like object, you borrow it from an array object using
the call() or apply() method.
See the following example:
let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 3,
prepend(message) {
[].unshift.call(this, message);
return this.length;
},
};
greetings.prepend('Good day');
console.log(greetings);
Output:
{
'0': 'Good day',
'1': 'Hi',
'2': 'Hello',
'3': 'Howdy',
length: 4,
prepend: [Function: prepend]
}
How it works.
First, de ne the greetings object that has
• The properties with the names 0, 1, and 3 represent the elements of
the greetings object.
• The length property is initialized with a value of 3, which indicates the number of
elements that the greetings object has.
• The prepend() method invokes the call() method of the unshift() method and sets
the this to the greetings object. In other words, the greetings object borrows
the unshift() method from an array object ([]).
fi
Second, call the prepend() method of the greetings object to add an element at the index 0th.
Third, output the greetings object to the console.
If you want to allow the prepend() method to add one or more elements to
the greetings object, you can use the rest parameter and spread operator like this:
let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 3,
prepend(...messages) {
[].unshift.call(this, ...messages);
return this.length;
},
};
In this example, the prepend() method accepts one or more messages (...messages) and
passes them into the unshift() method individually using the spread operator.
Summary
• Use the JavaScript array unshift() method to add one or more elements to the beginning of an array.
• The unshift() method also works with the array-like object by using the call() or apply() method.
pop()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array pop() method to remove
the last element from an array.
array.pop()
The pop() method changes the length property of the array. If the array is empty,
the pop() returns unde ned.
1) Using the JavaScript array pop() method to remove the last element of an array
The following example uses the pop() method to remove the last element of the numbers array:
console.log(last); // 30
console.log(numbers.length); // 2
Output:
30
2
In this example, the pop() method removes the number 30 from the numbers array. Also, it
decreases the value of the length property of the numbers array to 2.
The following picture illustrates how the pop() method works:
fi
2) Using the JavaScript array pop() method with an empty array
The following example calls the pop() method on an empty array. In this case, the pop() method
returns unde ned and the length is of the array is zero:
console.log(last);
console.log(numbers.length);
Output:
unde ned
0
let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 2,
removeLast() {
return [].pop.call(this);
},
};
console.log(greting);
console.log(greetings);
Output:
'Howdy'
{
'0': 'Hi',
'1': 'Hello',
length: 2,
removeLast: [Function: removeLast]
}
fi
fi
How it works.
Third, output the removed element (greeting) and the greetings object to the console:
console.log(greting);
console.log(greetings);
Summary
• Use the pop() method to remove the last element of an array.
• Use the call() or apply() to call the pop() method on an array-like object.
fi
shift()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array shift() method to remove the
rst element from an array.
array.shift()
If the array is empty, the shift() method returns unde ned. Otherwise, it returns the removed
element. Also, the shift() method reduces the length property of the array by one.
If you want to remove the last element from an array, you can use the pop() method.
Note that the shift() method has to reindex all the remaining elements of an array. Therefore,
it’s slower in comparison with the pop() method.
Output:
{ number: 10 }
{ numbers: [ 20, 30 ] }
{ length: 2 }
fi
fi
fi
fi
How it works.
First, de ne the numbers array that has three elements:
Second, remove the rst element from the numbers array and assign the removed element to
the number variable.
Third, output the removed element, array, and the array’s length to the console:
Output:
10
20
30
fi
fi
fi
Using the JavaScript array shift() with array-like object
The shift() method is generic. Therefore, you can use it with array-like objects. To use
the shift() method with an array-like object, you use the call() or apply() method.
Consider the following example:
let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 3,
removeFirst() {
return [].shift.call(this);
},
};
console.log(greeting);
console.log(greetings);
Output:
Hi
{
'0': 'Hello',
'1': 'Howdy',
length: 2,
removeFirst: [Function: removeFirst]
}
How it works.
First, de ne the greetings object:
let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 3,
removeFirst() {
return [].shift.call(this);
},
};
fi
The greetings object has three elements denoted by the properties 0, 1, and 2. Also, it has
the length property that stores the number of elements of the object.
The removeFirst() method uses the call() method to invoke the shift() method of an array with
the this references to the greetings object.
Second, call the removeFirst() method and assigned the removed element to the greeting variable:
console.log(greeting);
console.log(greetings);
The output shows that the length is reduced by one, the property with the index 0 is removed,
and the indexes of other properties were adjusted accordingly.
Summary
• Use the shift() method to remove the rst element from an array and return that element.
• Use the shift() method with an array-like object via the call() or apply() method.
fi
splice()
Summary: this tutorial shows you how to use the JavaScript Array’s splice() method to delete
existing elements, insert new elements, and replace elements in an array.
JavaScript Array type provides a very powerful splice() method that allows you to insert new
elements into the middle of an array. However, you can use this method to delete and
replace existing elements as well.
Array.splice(position,num);
The position speci es the position of the rst item to delete and the num argument determines the
number of elements to delete.
The splice() method changes the original array and returns an array that contains the deleted
elements.
The following statement deletes three elements of the scores array starting from the rst element.
console.log(scores); // [4, 5]
console.log(deletedScores); // [1, 2, 3]
fi
fi
fi
fi
The following gure illustrates the scores.splice(0,3) method call above.
Array.splice(position,0,new_element_1,new_element_2,...);
In this syntax:
• The position speci es the starting position in the array that the new elements will be inserted.
• The second argument is zero (0) that instructs the splice() method to not delete any array
elements.
• The third argument, fourth argument, and so on are the new elements that are inserted into
the array.
Note that the splice() method actually changes the original array. Also, the splice() method does not
remove any elements, therefore, it returns an empty array. For example:
Assuming that you have an array named colors with three strings.
The following statement inserts one element after the second element.
colors.splice(2, 0, 'purple');
The colors array now has four elements with the new element inserted in the second position.
You can insert more than one element by passing the fourth argument, the fth argument, and so
on to the splice() method as in the following example.
languages.splice(1, 1, 'Python');
The languages array now still has four elements with the new second argument is 'Python' instead of ‘C++'.
console.log(languages);
// ["C", "Python", "Java", "JavaScript"]
fi
fi
fi
The following gure illustrates the method call above.
You can replace one element with multiple elements by passing more arguments into the splice() method
as follows:
languages.splice(2,1,'C#','Swift','Go');
The statement deletes one element from the second element i.e., Java and inserts three new
elements into the languages array. The result is as follows.
In this tutorial, you have learned how to use the JavaScript Array splice() method to delete
existing elements, insert new elements, and replace elements in an array.
fi
slice()
The Array.prototype object provides the slice() method that allows
you to extract subset elements of an array and add them to the
new array. In this tutorial, we will show you the practical uses of
the JavaScript array slice() method.
slice(start, stop);
The start parameter determines the zero-based index at which to start extraction. If the start is unde ned, slice() begins at 0.
The stop parameter, as its name implies, is a zero-based index at which to end extraction. The slice() method extracts up
to stop-1. It means that the slice() method doesn’t include the element at the stop position in the new array. If you omit
the stop parameter, the slice() method will use the length of the array for the stop parameter.
The slice() returns a new array that contains the elements of the original array. It’s important to keep in mind that
the slice() method performs the shallow copy of elements to the new array only. In addition, it doesn’t change the source
array.
Clone an array
The slice() is used to clone an array as shown in the following example:
In this example, the newNumbers array contains all the elements of the numbers array.
The rgb array contains the rst three elements of the colors array. The source array colors remains intact.
fi
fi
Convert array-like objects into arrays
The slice() method is used to convert an array-like object into an array. For example:
function toArray() {
return Array.prototype.slice.call(arguments);
}
In this example, the arguments of the toArray() function is an array-like object. Inside
the toArray() function, we called the slice() method to convert the arguments object into an array.
Every argument we pass to the toArray() function will be the elements of the new array.
Another typical example that you often see is converting a NodeList into an array as follows:
var p = document.querySelectorAll('p');
var list = Array.prototype.slice.call(p);
In this example, rst, we used the document.querySelectorAll() to get all p nodes of the HTML
document. The result of this method is a NodeList object, which is an array-like object. Then, we
called the slice() method to convert the NodeList object into an array.
In this example, we instantiated an empty array [] and indirectly accessed the slice() method of
the Array.prototype method through the empty array. The effect is the same as the one that uses
the Array.prototype directly.
In this tutorial, you have learned how to use the JavaScript array slice() method to copy an entire or
a subset of the array and convert an array-like object into an array.
fi
fi
fi
Section 3. Finding elements
indexOf()
Summary: in this tutorial, we will show you how to use the JavaScript array indexOf() and lastIndexOf() methods to nd
the position of an element in an array.
Array.indexOf(searchElement, fromIndex)
1. The searchElement argument is the element that you want to nd in the array.
2. The fromIndex is an array index at which the function starts the search.
The fromIndex argument can be a positive or negative integer. If the fromIndex argument is
negative, the indexOf() method starts searching at array’s length plus fromIndex.
In case you omit the fromIndex argument, the indexOf() method starts searching from the begining
of the string.
Notice that the indexOf() method uses the strict equality comparison algorithm that is similar to the
triple-equals operator (===) when comparing the searchElement with the elements in the array.
The following example uses the indexOf() method to nd the elements in the scores array:
console.log(scores.indexOf(10)); // 0
console.log(scores.indexOf(30)); // 2
console.log(scores.indexOf(50)); // -1
console.log(scores.indexOf(20)); // 1
fi
fi
fi
fi
fi
fi
And the following example uses the fromIndex() with the negative values:
Assuming that you have the following array of objects, where each object has two properties: name and age.
var guests = [
{name: 'John Doe', age: 30},
{name: 'Lily Bush', age: 20},
{name: 'William Gate', age: 25}
];
The following statement returns -1 even though the rst element of the guests array and
the searchElement have the same values in the name and ages properties. This is because
they are two different objects.
console.log(guests.indexOf({
name: 'John Doe',
age: 30
})); // -1
Sometimes, you want to nd the indices of all occurrences of an element in an array. The
following nd() function uses the indexOf() method to do so.
The lastIndexOf() method returns the index of the last occurrence of the searchElement in the
array. It returns -1 if it cannot nd the element.
Different from the indexOf() method, the lastIndexOf() method searches for the element backward,
starting at fromIndex.
The following statements return the last indices of the number 10 and 20 in the scores array.
console.log(scores.lastIndexOf(10));// 3
console.log(scores.lastIndexOf(20));// 5
Because the number 50 is not in the scores array, the following statement returns -1.
console.log(scores.lastIndexOf(50));// -1
In this tutorial, you have learned how to use the JavaScript array indexOf() and lastIndexOf() methods to
locate an element in the array.
fi
fi
fi
includes()
Summary: this tutorial introduces you the JavaScript
Array includes() method that checks if an element is in an array.
The indexOf() method returns the index of the rst occurrence of the element in the array. If
the array doesn’t include the element, the indexOf() returns -1.
As you can see, the indexOf() method doesn’t really clearly state what it means. In addition,
the indexOf() uses strict equality operator (===) for comparison, therefore, it doesn’t work
with NaN as shown in the following example:
[NaN].indexOf(NaN); // -1
In this example, the array contains one element of NaN. However, the indexOf(NaN) returns -1.
To work around this, developers came up with a helper function, for example, Lodash provides
the _.incudes() method that checks if a value is in the array.
The includes() method returns true if an array contains a given element; Otherwise, it returns false.
array.includes(element,fromIndex);
[1,2,3].includes(2); // true
[1,2,3].includes(4); // false
[1,2,3].includes(1,1); // false
Unlike the indexOf() method, the includes() method works perfectly ne with the NaN:
[NaN].includes(NaN); // true
Note that the includes() doesn’t distinguish between +0 and -0 as shown in the following example:
[-0].includes(+0); // true
The following example demonstrates how to use the includes() method to check if an object is in an array.
console.log(cars.includes(ford)); // true
console.log(cars.includes(bmw)); // false
In this example:
• First, we initialized the cars array with two objects: ford and toyota.
• Then, we used the includes() method to check if the cars array contains the ford object,
in this case, it returns true.
• Finally, the bmw object is not in the cars array, therefore, the includes() method
returns true as expected.
In this tutorial, you have learned how to use the JavaScript Array includes() method to check
if an element is in an array.
fi
nd()
Summary: in this tutorial, you will learn how to use the JavaScript nd() method to search for
the rst element in an array, which satis es a test.
ES6 introduced a new method called nd() added to the Array.prototype object.
The nd() method returns the rst element in an array that passes a test function. The following
shows the syntax of the nd() method:
Arguments
The nd() accepts two arguments: a callback function and an optional value to use for
the this inside the callback function.
1) callback
The callback is a function that executes each element of the array. It takes three arguments:
• element is the current element.
• index the index of the current element.
• array the array that the nd() was called upon.
2) thisArg
The thisArg is the object used as this inside the callback.
Return value
The nd() executes the callback function for each element in the array until the callback returns a
truthy value.
If the callback returns a truthy value, the nd() immediately returns the element and stops
searching. Otherwise, it returns unde ned.
If you want to nd the index of the found element, you can use the ndIndex() method.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
JavaScript nd() examples
The following example uses the nd() method to search for the rst even number in an array
of numbers:
Output:
Suppose that we have a list of customer objects with name and credit properties as follows:
let customers = [{
name: 'ABC Inc',
credit: 100
}, {
name: 'ACME Corp',
credit: 200
}, {
name: 'IoT AG',
credit: 300
}];
The following code uses the nd() method to nd the rst customer whose credit is greater
than 100.
Output:
Summary
• Use the nd() method to nd the rst element of an array that satis es a provided testing
function.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
ndIndex()
Summary: in this tutorial, you will learn how to use the Array ndIndex() method to nd the rst
element that satis es a given test.
1) testFn
he testFn is a function to execute on each element in the array until the function returns true,
indicating that the element has been found.
The testFn takes three arguments:
• element is the current element in the array.
• index is the index of the current element being processed.
• array is the array that the ndIndex() was called upon.
2) thisArg
The thisArg is an optional object to be used this when executing the callback. If you omit
the thisArg argument, the ndIndex() function uses unde ned.
The ndIndex() executes the testFn on every element in the array until it nds the one
where testFn returns a truthy value, which is a value that coerces to true.
Once the ndIndex() nds such an element, it immediately returns the element’s index.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
JavaScript Array ndIndex() examples
Let’s take some examples of using the JavaScript Array ndIndex() method.
Output:
console.log(index);
Output:
const products = [
{ name: 'Phone', price: 999 },
{ name: 'Computer', price: 1999 },
{ name: 'Tablet', price: 995 },
];
console.log(index); // 1
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Section 4. High-order methods
map()
Summary: in this tutorial, you will learn how to use the JavaScript Array map() method to
transform elements in an array.
Typically, you use a for loop to iterate over the elements, transform each individual one, and push the
results into a new array.
Suppose that you have an array of numbers where each element represents the radius of a circle as
follows:
let circles = [
10, 30, 50
];
The following illustrates how to calculate the area of each circle and push the result into a new array.
Output
Starting from ES5, JavaScript Array type provides the map() method that allows you to transform
the array elements in a cleaner way.
fl
function circleArea(radius) {
return Math. oor(Math.PI * radius * radius);
}
let areas = circles.map(circleArea);
console.log(areas);
Output
How it works.
• First, de ne a function that calculates the area of a circle.
• Then, pass the circleArea function to the map() method. The map() method will call
the circleArea function on each element of the circles array and return a new array with
the elements that have been transformed.
To make it shorter, you can pass in the map() method an anonymous function as follows.
Also, you can make use of the arrow function in ES6 to achieve the same result with a cleaner code:
arrayObject.map(callback[,contextObject]);
The map() method calls a callback function on every element of an array and returns a new
array that contains the results.
The map() method takes two named arguments, the rst one is required whereas the second
one is optional.
Similar to the other iterative method such as every(), some(), lter(), forEach() and sort(),
the callback() function has the following form:
fi
fl
fl
fl
fi
fi
function callback(currentElement,index,array){
// ...
}
Output
[4, 5, 6]
The new array contains the square roots of the numbers in the numbers array.
In this tutorial, you have learned how to use the JavaScript Array map() method to transform
elements of an array according to a provided function.
lter()
Summary: in this tutorial, you will learn how to use the JavaScript Array lter() method to
lter elements in an array.
Suppose you have an array of city objects where each object contains two
properties: name and population.
let cities = [
{name: 'Los Angeles', population: 3792621},
{name: 'New York', population: 8175133},
{name: 'Chicago', population: 2695598},
{name: 'Houston', population: 2099451},
{name: 'Philadelphia', population: 1526006}
];
To nd the city whose population is greater than 3 million, you typically loop over the array elements using
a for loop and test if the value of the population property satis es the condition, like this:
Output:
[
{ name: 'Los Angeles', population: 3792621 },
{ name: 'New York', population: 8175133 }
]
JavaScript Array provides the lter() method that allows you to do this task in a shorter and cleaner way.
fi
fi
fi
fi
fi
fi
fi
The following example returns the same result as the example above:
In this example, we call the lter() method of the cities array object and pass a function that
tests each element.
Inside the function, we check if the population of each city in the array is greater than 3
million. If it is the case, the function returns true or false otherwise.
The lter() method includes the only elements in the result array if they satisfy the test in the
callback function.
Starting with ES6, you can use the arrow function to make it more concise:
console.log(bigCities);
The lter() method creates a new array with all the elements that pass the test implemented by
the callback() function.
Internally, the lter() method iterates over each element of the array and passes each element to
the callback function. If the callback function returns true, it includes the element in the return array.
The lter() method accepts two named arguments: a callback function and an optional object.
For example, the following illustrates how to chain the three methods: lter(),sort(), and map():
cities
. lter(city => city.population < 3000000)
.sort((c1, c2) => c1.population - c2.population)
.map(city => console.log(city.name + ':' + city.population));
Output:
Philadelphia:1526006
Houston:2099451
Chicago:2695598
How it works.
• First, lter the cities whose populations are less than 3 million using the lter() method.
• Second, sort the resulting cities by the populations in descending order using
the sort() method.
• Third, output array element to the console using the map() method.
The following example illustrates the use of the contextObject argument that speci es an
object which can be referenced in the callback() function using the this keyword
fi
fi
fi
fi
fi
fi
fi
fi
fi
function isInRange(value) {
if (typeof value !== 'number') {
return false;
}
return value >= this.lower && value <= this.upper;
}
let data = [10, 20, "30", 1, 5, 'JavaScript lter', unde ned, 'example'];
let range = {
lower: 1,
upper: 10
};
console.log(numberInRange); // [10, 1, 5]
Output:
[ 10, 1, 5 ]
How it works.
• First, de ne the isInRange() function that checks if its argument is a number and in the
range speci ed by the lower and upper properties of an object.
• Next, de ne an array of mixed data that contains numbers, strings, and unde ned.
• Then, de ne the range object with two properties lower and upper.
• After that, call the lter() methods of the data array and pass in the isInRange() function
and the range object. Because we pass in the range object, inside
the isInRange() function, the this keyword references to the range object.
• Finally, show the result array in the console.
In this tutorial, you have learned how to use the JavaScript Array lter() method to lter
elements in an array based on a test provided by a callback function.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
reduce()
Summary: in this tutorial, you will learn how to use the JavaScript Array reduce() and reduceRight() methods to
reduce an array to a value.
Typically, you use a for loop to iterate over the elements and add them up as shown in the following example:
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
Output:
The Array.prototype allows you to reduce an array to a single value using the reduce() method like this:
console.log(sum);
It’s pretty simple, isn’t it?
Let’s take a look at the reduce() method in detail.
array.reduce(callbackFn [, initialValue])
The reducer() function returns a value that results from executing the callbackFn to completion over
the entire array.
previousValue
The value returned from the previous call of the callbackFn function. On the rst call,
the initialValue is the previousValue if you pass the initialValue. Otherwise, its value is the array[0].
currentValue
The value of the current array element. On the rst call, it is array[0] if you pas
the initialValue or array[1] otherwise.
currentIndex
The index of the currentValue in the array. On the rst call, it’s 0 if you pass the initialValue or 1
otherwise.
array
If you specify the initialValue, the callbackFn function will initialize the previousValue to
the initialValue and currentValue to the rst array’s element on the rst call.
If you don’t specify the initialValue, the the callbackFn function will initialize the previousValue to
the rst array’s element (array[0]) in the array and the currentValue to the second array’s element
(array[1]).
The following table illustrates the logic when the reduce() method executes
the callbackFn() function for the rst time according to the initialValue argument:
The following example shows the progress of the reduce() function with an initialValue as 100:
let call = 1;
let sum = numbers.reduce(function (previousValue, currentValue, currentIndex, array) {
let result = previousValue + currentValue;
return result;
},100);
console.log(`Result: ${sum}`);
fi
ffi
fi
ffi
fi
fi
Output:
1st call
(index) Values
previousValue 100
currentValue 1
currentIndex 0
result 101
2nd call
(index) Values
previousValue 101
currentValue 2
currentIndex 1
result 103
3rd call
(index) Values
previousValue 103
currentValue 3
currentIndex 2
result 106
Result: 106
And the following illustrates the reduce() method without the initialValue argument:
1st call
(index) Values
previousValue 1
currentValue 2
currentIndex 1
result 3
2nd call
(index) Values
previousValue 3
currentValue 3
currentIndex 2
result 6
Result: 6
More JavaScript Array reduce() examples
Suppose that you have the following shoppingCart array of product objects:
let shoppingCart = [
{
product: 'phone',
qty: 1,
price: 500,
},
{
product: 'Screen Protector',
qty: 1,
price: 10,
},
{
product: 'Memory Card',
qty: 2,
price: 20,
},
];
To calculate the total amount of the products in the shopping cart, you can use the reduce() method,
like this:
Output:
550
Notice that in this example, we passed in the initialValue argument to the reduce() method.
If we didn’t do so, the reduce() method would take the rst element of the shoppingCart array,
which is an object, as an initial value and perform the calculation on this object. Hence, it would
cause an incorrect result.
fi
JavaScript Array reduceRight() method
The reduceRight() method works in the same way as the reduce() method, but in the opposite direction.
The reduce() method starts at the rst element and travels toward the last, whereas
the reduceRight() method starts at the last element and travels backward the rst.
console.log(`Result:${sum}`);
Output
{ previousValue: 3, currentValue: 2 }
{ previousValue: 5, currentValue: 1 }
Result:6
The following picture illustrates the difference between the reduce() and reduceRight() methods:
In this tutorial, you have learned how to use the JavaScript array reduce() and reduceRight() methods
to reduce an array into a value.
fi
fi
every()
Summary: in this tutorial, you will learn how to check whether all the array elements pass a
test using the JavaScript Array every() method.
Typically, you use a for loop to iterate all elements and check each individual element against the
condition. Suppose that you have an array numbers with three elements:
The following code checks if every element in the numbers array is greater than zero:
Output:
true
How it works:
• First, initialize the result variable to true.
• Second, iterate over the elements of the numbers array and check whether each element is
less than or equal zero. If it is the case, set the result variable to false and terminate the loop
immediately using the break statement. In case no element is less than or equal zero, the
value of the result variable remains true.
This code is simple and straight forward. However, it is quite verbose.
JavaScript Array type provides the every() method that allows you to check if every element of an
array pass a test in a shorter and cleaner way.
fi
fi
Introduction to JavaScript Array every() method
Starting from ES5, JavaScript Array type provides a method every() that tests every element in an array.
The following example uses the every() to check if every element of the numbers array is greater than
zero:
console.log(result);
Output:
true
By using the ES6 arrow functions, the code can be even shorter:
console.log(result);
arrayObject.every(callback[, thisArg])
The every() method accepts two named arguments: callback and thisArg.
1) The callback argument
The callback is a function that tests each element of the array. The callback() function has the following form:
console.log(isEven);
Output:
false
fi
In contrast, the following example tests if all the array elements are the odd numbers.
console.log(isOdd);
Output:
true
Suppose that you have an object with two properties: min and max:
let range = {
min: 0,
mas: 10
};
The following example tests whether all elements in the numbers array is in the range speci ed by
the min and max of the range object.
let range = {
min: 0,
max: 10
};
Output:
true
In this example, we pass the range object to the every() method as the second argument. And
inside the callback() function, we reference the range object using the this keyword.
fi
Caution: Empty arrays
If you call the every() method on an empty array, the method will always return true for any
condition. For example:
console.log('gtZero:', gtZero);
console.log('ltZero:', ltZero);
Output:
gtZero: true
ltZero: true
In this tutorial, you have learned how to use the JavaScript Array every() method to test whether all
elements in an array pass the test provided by a test function.
some()
Summary: in this tutorial, you will learn how to use the JavaScript Array some() method to check if
at least one element in the array passes a test.
console.log(lessThanFive);
Output:
true
How it works:
• First, declare a ag variable lessThanFive and set its value to false.
• Second, iterate over the elements. If an element is less than 5, set the ag to true and
immediately exit the loop using the break statement.
The code works as expected. However, it is quite verbose.
The Array type provides you with an instance method called some() that allows you to test if
an array has at least one element that meets a condition.
fl
fl
fi
let marks = [ 4, 5, 7, 9, 10, 3 ];
lessThanFive = marks.some(function(e) {
return e < 5;
});
console.log(lessThanFive);
Output
true
The condition is implemented via a callback function passed into the some() method.
Now, the code is shorter. To make it more expressive, you can use the arrow function syntax in ES6:
console.log(lessThanFive);
arrayObject.some(callback[, thisArg]);
If no element causes the callback() to return true, the some() method returns false.
console.log(exists(4, marks));
console.log(exists(11, marks));
Output:
true
false
console.log(result);
Output:
true
How it works.
• First, de ne a range object with min and max properties.
• Second, call the some() method on the marks array object and pass the callback and
range object. Because we pass the range object as the second argument (thisArg), we
can reference it inside the callback via the this value.
Notice that if you use the arrow function in this example, the this value inside the callback
function doest not bind to the range object but the global object.
Output:
false
false
In this tutorial, you have learned how to use the JavaScrip Array some() method to test if an array
has at least one element that meets a condition.
fi
sort()
Summary: in this tutorial, you will learn how to use the JavaScript Array sort() method to sort
arrays of numbers, string, and objects.
By default, the sort() method sorts the array elements in ascending order with the smallest value
rst and largest value last.
The sort() method casts elements to strings and compares the strings to determine the orders.
[ 0, 1, 10, 2, 20, 3, 30 ]
In this example, the sort() method places 10 before 2 because the string “10” comes before “2”
when doing a string comparison.
To x this, you need to pass a compare function to the sort() method. The sort() method will use the
compare function to determine the orders of elements.
array.sort(comparefunction)
The sort() method accepts an optional argument which is a function that compares two elements of
the array.
If you omit the compare function, the sort() method sorts the elements with the sort order based on
the Unicode code point values of elements as mentioned earlier.
The compare function of the sort() method accepts two arguments and returns a value that
determines the sort order. The following illustrates the syntax of the compare function:
function compare(a,b) {
// ...
}
fi
fi
The compare() function accepts two arguments a and b. The sort() method will sort elements based
on the return value of the compare() function with the following rules:
1. If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other
words, a will come rst.
2. If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b
will come rst.
3. If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions
unchanged.
To x the issue of sorting the number, you can use the following syntax:
console.log(numbers);
Output:
[ 0, 1, 2, 3, 10, 20, 30 ]
Or you can de ne the comparison function using the arrow function syntax:
console.log(numbers);
And the following is the simplest since the elements of the array are numbers:
console.log(numbers);
fi
fi
fi
fi
Sorting an array of strings
Suppose you have an array of string named animals as follows:
let animals = [
'cat', 'dog', 'elephant', 'bee', 'ant'
];
To sort the elements of the animals array in ascending order alphabetically, you use
the sort() method without passing the compare function as shown in the following example:
let animals = [
'cat', 'dog', 'elephant', 'bee', 'ant'
];
animals.sort();
console.log(animals);
Output:
To sort the animals array in descending order, you need to change the logic of the compare
function and pass it to the sort() method as the following example.
let animals = [
'cat', 'dog', 'elephant', 'bee', 'ant'
];
animals.sort((a, b) => {
if (a > b)
return -1;
if (a < b)
return 1;
return 0;
});
console.log(animals);
Output:
To sort this array alphabetically, you need to use a custom compare function to convert all elements
to the same case e.g., uppercase for comparison and pass that function to the sort() method.
let mixedCaseAnimals = [
'Cat', 'dog', 'Elephant', 'bee', 'ant'
];
mixedCaseAnimals.sort(function (a, b) {
let x = a.toUpperCase(),
y = b.toUpperCase();
return x == y ? 0 : x > y ? 1 : -1;
});
Output:
console.log(animaux);
As you see, the écureuil string should come before the zèbre string.
To resolve this, you use the localeCompare() method of the String object to compare strings in a
speci c locale, like this:
animaux.sort(function (a, b) {
return a.localeCompare(b);
});
console.log(animaux);
fi
fi
Output:
The elements of the animaux array now are in the correct order.
let scores = [
9, 80, 10, 20, 5, 70
];
To sort an array of numbers numerically, you need to pass into a custom comparison function
that compares two numbers.
The following example sorts the scores array numerically in ascending order.
let scores = [
9, 80, 10, 20, 5, 70
];
// sort numbers in ascending order
scores.sort((a, b) => a - b);
console.log(scores);
Output:
To sort an array of numbers numerically in descending order, you just need to reverse the
logic in the compare function as shown in the following example:
let scores = [
9, 80, 10, 20, 5, 70
];
// descending order
scores.sort((a, b) => b - a);
console.log(scores);
Output:
let employees = [
{name: 'John', salary: 90000, hireDate: "July 1, 2010"},
{name: 'David', salary: 75000, hireDate: "August 15, 2009"},
{name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];
// sort by salary
employees.sort(function (x, y) {
return x.salary - y.salary;
});
console.table(employees);
Output:
This example is similar to the example of sorting an array of numbers in ascending order.
The difference is that it compares the salary property of two objects instead.
fi
Sorting objects by a string property
To sort the employees array by name property case-insensitively, you pass the compare function
that compares two strings case-insensitively as follows:
employees.sort(function (x, y) {
let a = x.name.toUpperCase(),
b = y.name.toUpperCase();
return a == b ? 0 : a > b ? 1 : -1;
});
console.table(employees);
employees.sort(function (x, y) {
let a = new Date(x.hireDate),
b = new Date(y.hireDate);
return a - b;
});
console.table(employees);
fi
Optimizing JavaScript Array sort() method
In fact, the sort() method calls the compare function multiple times for each element in the array.
rivers.sort(function (a, b) {
console.log(a, b);
return a.length - b.length;
});
Output:
Amazon Nile
Congo Amazon
Congo Amazon
Congo Nile
Mississippi Congo
Mississippi Amazon
Rio-Grande Amazon
Rio-Grande Mississippi
How it works:
1. First, declare an array rivers that consists of the famous river names.
2. Second, sort the rivers array by the length of its element using the sort() method.
We output the elements of the rivers array to the web console whenever
the sort() method invokes the comparison function .
As shown in the output above, each element has been evaluated multiple times e.g., Amazon
4 times, Congo 2 times, etc.
If the number of array elements is increasing, it will potentially decrease the performance.
You cannot reduce the number of times that comparison function is executed. However, you
can reduce the work that the comparison has to do. This technique is called Schwartzian
Transform.
To implement this, you follow these steps:
1. First, extract the actual values into a temporary array using the map() method.
2. Second, sort the temporary array with the elements that are already evaluated (or
transformed).
3. Third, walk the temporary array to get an array with the right order.
Here is the solution:
console.log(sortedRivers);
Output:
In this tutorial, you have learned how to use the JavaScript Array sort() method to sort arrays
of strings, numbers, dates, and objects.
forEach()
Summary: in this tutorial, you will learn how to use the JavaScript Array forEach() method to
exeucte a function on every element in an array.
Output:
A
B
C
JavaScript Array provides the forEach() method that allows you to run a function on every element.
The following code uses the forEach() method that is equivalent to the code above:
ranks.forEach(function (e) {
console.log(e);
});
Output:
A
B
C
The forEach() method iterates over elements in an array and executes a prede ned function once per element.
Array.forEach(callback [, thisArg]);
1) callback
The callback function that the forEach() method uses to execute on every element.
2) thisArg
The thisArg is a value to use as this when executing the callback.
Note that the forEach() function returns unde ned therefore it is not chainable like other iterative
methods: lter(), map(), some(), every(), and sort().
One limitation of the forEach() method in comparison with the for loop is that you cannot use
the break or continue statement to control the loop.
To terminate the loop in the forEach() method, you must throw an exception inside
the callback function.
function Counter() {
this.count = 0;
let self = this;
return {
increase: function () {
self.count++;
},
current: function () {
return self.count;
},
reset: function () {
self.count = 0;
}
}
}
fi
fi
fi
This example shows how to pass the counter object to the forEach() method.
console.log(sum); // 6
console.log(counter.current()); // 3
How it works.
• First, create a new Counter object.
• Next, de ne an array of three numbers.
• Then, declare a variable sum and assign it a value of zero.
• After that, call the forEach() method on the numbers array. In the callback function, add
the element to the sum variable and call the increase() method of the counter object.
Notice that the counter object is referred to as this inside the callback function.
• Finally, log the value of the sum and current value of the counter in the web console.
In this tutorial, you have learned how to use the JavaScript Array forEach() method to
execute a callback on every element of an array.
fi
Section 5. Manipulating Arrays
concat()
Summary: in this tutorial, you will learn how to use the JavaScript Array concat() method to
merge two or more arrays into a single array.
To merge two or more arrays, you use the concat() method of an Array object. The concat() method
returns a new array and doesn’t change the original arrays. For example:
console.log('Result:', combined);
console.log('Odds:', odds);
Output:
Result: [ 1, 3, 5, 2, 4, 6 ]
Odds: [ 1, 3, 5 ]
array method to merge elements of the two arrays. The elements of the second array are
appended to the elements of the rst array.
Similarly, you can call the concat() method on an empty array denoted by ([]):
console.log(combined);
Output:
[ 1, 3, 5, 2, 4, 6 ]
fi
The concat() method allows you to merge more than two arrays as shown in the following example:
Output:
In this example, we merge the three arrays: upper, lower, and digits.
When you don’t pass any argument into the concat() method, it simply clones the array and returns it:
Output:
If you pass values that are not arrays, into the concat() method, the method will appends each value
to the end of the result array:
Output:
In ES6, you can use spread operator to merge multiple arrays as follows:
Output:
[ 1, 3, 5, 2, 4, 6 ]
Section 6. Creating Arrays
of()
Summary: in this tutorial, you will learn how to improve array construction using the
JavaScript Array.of() method in ES6.
However, when you pass to the Array constructor a value that is not a number, JavaScript creates
an array that contains one element with that value. For example:
This behavior is sometimes confusing and error-prone because you may not know the type of
data that you pass to the Array constructor.
ES6 introduces the Array.of() method to solve this problem.
The Array.of() method is similar to the Array constructor except the Array.of() method does
not treat a single numeric value special.
In other words, the Array.of() method always creates an array that contains the values that
you pass to it regardless of the types or the number of arguments.
The following shows the syntax of the Array.of() method:
In this example, we passed the number 3 to the Array.of() method. The Array.of() method creates
an array of one number.
In this example, we created an array of three strings by passing 'A', 'B', and 'C' to the Array.of() method.
The size of the array is 3.
if (!Array.of) {
Array.of = function() {
return Array.prototype.slice.call(arguments);
};
}
In this tutorial, you have learned how to improve array construction using the JavaScript Array.of() method
in ES6.
fi
fi
from()
Summary: in this tutorial, you will learn about the JavaScript Array.from() method that creates a
new array from an array-like or iterable object.
function arrayFromArgs() {
var results = [];
for (var i = 0; i < arguments.length; i++) {
results.push(arguments[i]);
}
return results;
}
var fruits = arrayFromArgs('Apple', 'Orange', 'Banana');
console.log(fruits);
Output:
To make it more concise, you can use the slice() method of the Array.prototype as follows:
function arrayFromArgs() {
return Array.prototype.slice.call(arguments);
}
var fruits = arrayFromArgs('Apple', 'Orange', 'Banana');
console.log(fruits);
ES6 introduces the Array.from() method that creates a new instance of the Array from an array-like
or iterable object. The following illustrates the syntax of the Array.from() method:
In this syntax:
• target is an array-like or iterable object to convert to an array.
• mapFn is the map function to call on every element of the array
• thisArg is the this value when executing the mapFn function.
The Array.from() returns a new instance of Array that contains all elements of the target object.
JavaScript Array.from() method examples
Let’s take some examples of using the Array.from() method.
function arrayFromArgs() {
return Array.from(arguments);
}
console.log(arrayFromArgs(1, 'A'));
Output:
[ 1, 'A' ]
In this example, we create an array from arguments of the arrayFromArgs() function and return the array.
function addOne() {
return Array.from(arguments, x => x + 1);
}
console.log(addOne(1, 2, 3));
Output:
[ 2, 3, 4 ]
In this example, we increased each argument of the addOne() function by one and add the result to
the new array.
C) JavaScript Array Array.from() with a this value
If the mapping function belongs to an object, you can optionally pass the third argument to
the Array.from() method. The object will represent the this value inside the mapping function.
Consider this example:
let doubler = {
factor: 2,
double(x) {
return x * this.factor;
}
}
let scores = [5, 6, 7];
let newScores = Array.from(scores, doubler.double, doubler);
console.log(newScores);
Output:
[ 10, 12, 14 ]
let even = {
*[Symbol.iterator]() {
for (let i = 0; i < 10; i += 2) {
yield i;
}
}
};
let evenNumbers = Array.from(even);
console.log(evenNumbers);
Output:
[0, 2, 4, 6, 8]
In this example:
• First, de ne the even object with the [System.iterator] that returns even numbers from 0 to 10.
• Then, use the Array.from() method to create a new array of even numbers from
the even object.
In this tutorial, you have learned how to use the JavaScript Array Array.from() method to create an
array from an array-like or iterable object.
fi
Section 7. Flattening arrays
at()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array at() method to at an array.
The depth parameter speci es how deep the method ats the array structure. It defaults to 1.
The following example shows how to at an array of numbers:
console.log( atNumbers);
Output:
[1, 2, 3, 4, 5]
In this example, we didn’t pass the depth argument into the at() method therefore the depth
is 1 by default. The at() method concatenated all the elements of the nested array [3,4,5] to
the elements of the new array.
Note that the at() method creates a new array and doesn’t change the original array:
console.log(numbers);
Output:
[ 1, 2, [ 3, 4, 5 ] ]
fl
fl
fl
fl
fl
fi
fl
fl
fl
fl
fl
fl
fl
fi
fl
fl
fl
The following example ats an array with two level depth:
console.log( atNumbers);
Output:
[1, 2, 3, 4, 5, 6, 7]
When you don’t know the depth level, you can pass the In nity into the at() method to recursively
concatenate all elements of the sub-arrays into the new array:
console.log( atNumbers);
If an array has empty slots, you can use the at() method to remove the holes, like this:
console.log(sequence);
Output:
[ 1, 2, 4, 5 ]
Summary
• Use the Array.prototype. at() method to at an array with the nested arrays.
• Use the depth argument to specify how deep the nested arrays should be attened. The
depth is 1 by default.
• The at() also removes the holes in the array with empty slots.
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
fi
fl
fl
fi
fl
fl
atMap()
Summary: in this tutorial, you’ll about the JavaScript Array atMap() method that maps each
element in an array using a mapping function and attens the result into a new array.
The map() method creates a new array whose elements are the results of a mapping function.
The atMap() method is the combination of the map() method followed by the at() method of depth 1.
The atMap() method rst maps each element in an array using a mapping function and then attens the
results into a new array.
let sentences = ["JavaScript Array atMap()", " ", "is", " ", "Awesome"];
Output:
[
[ 'JavaScript', 'Array', ' atMap()' ],
[ ' ' ],
[ 'is' ],
[ ' ' ],
[ 'Awesome' ]
]
The result is an array of nested arrays lled by words. To atten the result, you can use
the at() method on the result of the map() method. However, it’ll be more concise to use
the atMap() method.
The atMap() creates a attened array by running each sentence in the array through a
mapping function and attening the mapped results:
let sentences = [
"JavaScript Array atMap()",
" ",
"is",
" ",
"Awesome"
];
let words = sentences. atMap(s => s.split(' '));
console.log(words);
Output:
[ 'JavaScript', 'Array', ' atMap()', '', '', 'is', '', '', 'Awesome' ]
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
fl
fi
fl
fl
2) Adding and removing elements during mapping example
The atMap() method allows you to add or remove elements during mapping. Consider the following example:
let cart = [{
name: 'Smartphone',
qty: 2,
price: 500,
freeOfCharge: false
},
{
name: 'Tablet',
qty: 1,
price: 800,
freeOfCharge: false
}
];
If customers buy a smartphone, you want to give them a free screen protector.
When the customer adds a smartphone to the cart, you can add a screen protector to the cart using
the atMap() method as follows:
console.log(newCart);
fl
fl
fl
The cart will look like this:
[
{ name: 'Smartphone', qty: 2, price: 500, freeOfCharge: false },
{ name: 'Screen Protector', qty: 2, price: 5, freeOfCharge: true },
{ name: 'Tablet', qty: 1, price: 800, freeOfCharge: false }
]
The following uses the reduce() method to calculate the total amount from the items in the
cart. It ignores the free-of-charge items, like screen protectors:
console.log({total});
Output:
{ total: 1800 }
Summary
• Use the atMap() method to create a attened array of elements by running each element in
the collection through a mapping function and attening the mapped results.
fl
fl
fl
Section 8. Arrays to Strings
join()
Summary: in this tutorial, you’ll learn how to use the JavaScript Array join() method to concatenate
all elements of an array into a string separated by a separator.
Array.prototype.join([separator])
The join() method accepts a optional argument separator which is a string that separates
each pair of adjacent elements of the array in the result string.
The separator defaults to a comma if you don’t pass it to the join() method.
In case the array has one element, the join() method returns that element as a string without
using the separator.
And if the array is empty, the join() method returns an empty string.
When the elements of the array aren’t strings, the join() method converts them to strings
before joining.
Note that the join() method converts unde ned, null, and empty array [] to an empty string.
console.log(btnClass);
Output:
2) Using the JavaScript Array join() method to replace all occurrences of a string
This example uses the JavaScript Array join() method to replace all occurrences of the space ' ' by the hyphen (-):
console.log(url);
Output:
javascript-array-join-example
How it works:
• First, split the title string by the space into an array by using the split() string method.
• Second, concatenate all elements in the result array into a string by using the join() method.
• Third, convert the result string to lower case by using the toLowerCase() method.
Summary
• Use the JavaScript Array join() method to concatenate all elements of an array into a
string separated by a separator.
Section 9. Advanced Operations
Destructuring
Summary: in this tutorial, you will learn how to use the ES6 destructuring assignment that
allows you to destructure an array into individual variables.
ES6 provides a new feature called destructing assignment that allows you to destructure
properties of an object or elements of an array into individual variables.
Let’s start with the array destructuring.
function getScores() {
return [70, 80, 90];
}
The following invokes the getScores() function and assigns the returned value to a variable:
let x = scores[0],
y = scores[1],
z = scores[2];
Prior to ES6, there was no direct way to assign the elements of the returned array to multiple
variables such as x, y and z.
Fortunately, starting from ES6, you can use the destructing assignment as follows:
console.log(x); // 70
console.log(y); // 80
console.log(z); // 90
The variables x, y and z will take the values of the rst, second, and third elements of the returned array.
Note that the square brackets [] look like the array syntax but they are not.
If the getScores() function returns an array of two elements, the third variable will be unde ned, like this:
function getScores() {
return [70, 80];
}
console.log(x); // 70
console.log(y); // 80
console.log(z); // unde ned
In case the getScores() function returns an array that has more than three elements, the remaining
elements are discarded. For example:
function getScores() {
return [70, 80, 90, 100];
}
console.log(x); // 70
console.log(y); // 80
console.log(z); // 90
The variables x and y receive values of the rst two elements of the returned array. And the args variable
receives all the remaining arguments, which are the last two elements of the returned array.
fi
fi
fi
fi
Note that it’s possible to destructure an array in the assignment that separates from the
variable’s declaration. For example:
let a, b;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20
function getItems() {
return [10, 20];
}
console.log(thirdItem); // 0
How it works:
• First, declare the getItems() function that returns an array of two numbers.
• Then, assign the items variable to the returned array of the getItems() function.
• Finally, check if the third element exists in the array. If not, assign the value 0 to
the thirdItem variable.
It’ll be simpler with the destructuring assignment with a default value:
console.log(thirdItem); // 0
If the value taken from the array is unde ned, you can assign the variable a default value, like this:
let a, b;
[a = 1, b = 2] = [10];
console.log(a); // 10
console.log(b); // 2
fi
fi
If the getItems() function doesn’t return an array and you expect an array, the destructing assignment will
result in an error. For example:
function getItems() {
return null;
}
let [x = 1, y = 2] = getItems();
Error:
Uncaught TypeError: getItems is not a function or its return value is not iterable
A typical way to solve this is to fallback the returned value of the getItems() function to an empty array like this:
function getItems() {
return null;
}
console.log(a); // 10
console.log(b); // 20
Since the third element of the returned array is another array, you need to use the nested
array destructuring syntax to destructure it, like this:
1) Swapping variables
The array destructuring makes it easy to swap values of variables without using a temporary variable:
let a = 10,
b = 20;
console.log(a); // 20
console.log(b); // 10
function stat(a, b) {
return [
a + b,
(a + b) / 2,
a-b
]
}
And then you use the array destructuring assignment syntax to destructure the elements of
the return array into variables:
In this tutorial, you have learned how to use the ES6 destructuring assignment to destructure
elements in an array into individual variables.
ff
ff
Spread operator
Summary: in this tutorial, you will learn about the JavaScript spread operator that spreads
out elements of an iterable object.
Output:
[ 2, 4, 6, 1, 3, 5 ]
In this example, the three dots ( ...) located in front of the odd array is the spread operator.
The spread operator (...) unpacks the elements of the odd array.
Note that ES6 also has the three dots ( ...) which is a rest parameter that collects all
remaining arguments of a function into an array.
f(1, 2, 3, 4, 5);
Output:
[ 3, 4, 5 ]
In this example, the rest parameter (...) collects the arguments 3, 4, and 5 into an array args. So
the three dots ( ...) represent both the spread operator and the rest parameter.
Here are the main differences:
• The spread operator (...) unpacks the elements of an iterable object.
• The rest parameter (...) packs the elements into an array.
The rest parameters must be the last arguments of a function. However, the spread operator
can be anywhere:
Output:
[ 1, 3, 5, 2, 4, 6 ]
Or
Output:
[ 2, 1, 3, 5, 4, 6 ]
Note that ES2018 expands the spread operator to objects, which is known as object
spread.
Let’s look at some scenarios where you can use the spread operators.
function compare(a, b) {
return a - b;
}
In ES5, to pass an array of two numbers to the compare() function, you often use the apply() method as
follows:
The spread operator spreads out the elements of the array so a is 1 and b is 2 in this case.
For example, the push() method of an array object allows you to add one or more elements to an array. If
you want to pass an array to the push() method, you need to use apply() method as follows:
[].push.apply(rivers, moreRivers);
console.log(rivers);
rivers.push(...moreRivers);
2) Concatenating arrays
Also, you can use the spread operator to concatenate two or more arrays:
Note that the spread operator only copies the array itself to the new one, not the
elements. This means that the copy is shallow, not deep.
In this example, we constructed the chars array from individual strings. When we applied the
spread operator to the 'BC'string, it spreads out each individual character of the string 'BC' into
individual characters.
Summary
• The spread operator is denoted by three dots (…).
• The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list.
• The rest paramter is also denoted by three dots (…). However, it packs the remaining arguments of
a function into an array.
• The spread operator can be used to clone an iterable object or merge iterable objects into one.
Section 10. Accesing elements
at()
Summary: in this tutorial, you will learn how to use the JavaScript Array at() method to return
an element by an index.
To get the last element in an array, you use the length property like this:
arr[length-1]
JavaScript doesn’t allow you to use a negative index to access the last element like other
languages e.g., Python. For example, the following returns unde ned:
arr[-1]
The reason is that JavaScript also uses square brackets [] for accessing a property of an object.
For example, the obj[1] returns a property of the object obj with the key "1". Hence,
the obj[-1] returns the property of an object with the key "-1".
In the above example, the arr[-1] returns the property of the arr object with the key "-1". Note that
the type of an array is object. Since the "-1" property doesn’t exist in the arr object, it
returns unde ned.
For this reason, ES2022 introduced a new method at() added to the prototype of Array, String,
and TypeArray. This tutorial focuses on the at() method of the Array.prototype.
The at() method accepts an index and returns an element at that index. Here’s the syntax of
the at() method:
arr.at(index)
In this syntax, the index speci es an array element to return. It can be zero, positive, or negative.
If the index is zero or positive, the at() method works like the [].
However, if you use a negative index, the method returns an element from the end of the array. For
example, the arr.at(-1) returns the last element, arr.at(-2) returns the second last element, and so on.
fi
fi
fi
fi
JavaScript Array at() method example
The following example shows how to use the at() method to return an array element:
Output:
6
7
true
Summary
• Use the at() method to return an element of an array by an index.
• The at() method with a negative index will return an element from the end of the array.
Section 11. Multidimensional Array
Multidimensional Array
Summary: in this tutorial, you will learn how to work with a JavaScript multidimensional array
and manipulate its elements effectively.
For this reason, we can say that a JavaScript multidimensional array is an array of arrays. The
easiest way to de ne a multidimensional array is to use the array literal notation.
To declare an empty multidimensional array, you use the same syntax as declaring one-
dimensional array:
let activities = [
['Work', 9],
['Eat', 1],
['Commute', 2],
['Play Game', 1],
['Sleep', 7]
];
In the activities array, the rst dimension represents the activity and the second one shows
the number of hours spent per day for each.
To show the activities array in the console, you use the console.table() method as follows:
console.table(activities);
fi
fi
fi
fi
The following illustrates the output:
(index) 0 1
0 ‘Work' 9
1 Eat' 1
2 ‘Commute' 2
3 ‘Play Game' 1
4 ‘Sleep' 7
Note that the (index) column is for the illustration that indicates the indices of the inner array.
To access an element of the multidimensional array, you rst use square brackets to access an element of
the outer array that returns an inner array; and then use another square bracket to access the element of
the inner array.
The following example returns the second element of the rst inner array in the activities array above:
console.log(activities[0][1]); // 9
For example, to add a new element at the end of the multidimensional array, you use the push() method as follows:
activities.push(['Study',2]);
console.table(activities);
(index) 0 1
0 Work' 9
1 Eat' 1
2 Commute' 2
3 Play Game' 1
4 Sleep' 7
5 Study' 2
To insert an element in the middle of the array, you use the splice() method. The following inserts an
element in the second position of the activities array:
(index) 0 1
0 'Work' 9
1 Programming' 2
2 Eat' 1
3 'Commute' 2
4 Play Game' 1
5 Sleep' 7
6 Study' 2
This example calculates the percentage of the hours spent on each activity and appends the
percentage to the inner array.
activities.forEach(activity => {
let percentage = ((activity[1] / 24) * 100).toFixed();
activity[2] = percentage + '%';
});
console.table(activities);
activities.pop();
console.table(activities);
Output:
(index) 0 1 2
0 Work' 9 38%'
1 Programming' 2 8%'
2 Eat' 1 4%'
3 Commute' 2 8%'
4 Play Game' 1 4%'
5 Sleep' 7 29%'
Similarly, you can remove the elements from the inner array of the multidimensional array by using
the pop() method. The following example removes the percentage element from the inner arrays of
the activities array.
activities.forEach((activity) => {
activity.pop(2);
});
console.table(activities);
Output:
(index) 0 1
0 Work' 9
1 Programming' 2
2 Eat' 1
3 Commute' 2
4 Play Game' 1
5 Sleep' 7
Iterating over elements of the JavaScript multidimensional array
To iterate a multidimensional array, you use a nested for loop as in the following example.
The rst loop iterates over the elements of the outer array and the nested loop iterates over
elements of the inner array.
The following shows the output of the script in the console:
[0,0] = Work
[0,1] = 9
[1,0] = Eat
[1,1] = 1
[2,0] = Commute
[2,1] = 2
[3,0] = Play Game
[3,1] = 1
[4,0] = Sleep
[4,1] = 7
[5,0] = Study
[5,1] = 2
activities.forEach((activity) => {
activity.forEach((data) => {
console.log(data);
});
});
fi
Output:
Work
9
Eat
1
Commute
2
Play Game
1
Sleep
7
Study
2
In this tutorial, you have learned how to use an array of arrays to create a JavaScript
multidimensional array.