[go: up one dir, main page]

0% found this document useful (0 votes)
2 views101 pages

5 Array Method

This document covers JavaScript Array properties and methods, including the length property, push(), unshift(), and pop(). It explains how the length property behaves for dense and sparse arrays, how to add and remove elements using push() and unshift(), and how to remove the last element using pop(). Additionally, it discusses the use of these methods with array-like objects.

Uploaded by

ROSHAN URKANDE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views101 pages

5 Array Method

This document covers JavaScript Array properties and methods, including the length property, push(), unshift(), and pop(). It explains how the length property behaves for dense and sparse arrays, how to add and remove elements using push() and unshift(), and how to remove the last element using pop(). Additionally, it discusses the use of these methods with array-like objects.

Uploaded by

ROSHAN URKANDE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Section 1.

Array properties

length property
Summary: in this tutorial, you’ll learn about the JavaScript Array length property and how to
handle it correctly.

What exactly is the JavaScript Array length property


By de nition, the length property of an array is an unsigned, 32-bit integer that is
always numerically greater than the highest index in the array.

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:

let colors = ['red', 'green', 'blue'];


console.log(colors.length); // 3

In this example, the length property returns three, which is the same as the number of elements in
the colors array.

The following adds one more element to the colors array:

colors.push('yellow');
console.log(colors.length); // 4

Now, the length property of the colors array is four.

When you empty the colors array, its length is zero:

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:

let numbers = [10, , 20, 30];


console.log(numbers.length); // 4

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

In this example, the length property returns 11.

Modifying JavaScript Array length property


JavaScript allows you to change the value of the array length property. By changing the value
of the length, you can remove elements from the array or make the array sparse.

1) Empty an array
If you set length to zero, the array will be empty:

const fruits = ['Apple', 'Orange', 'Strawberry'];


fruits.length = 0;

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:

const fruits = ['Apple', 'Orange', 'Strawberry'];


fruits.length = 2;

console.log(fruits); // [ 'Apple', 'Orange' ]


3) Make array sparse
If you set the length property of an array to a value that is higher than the highest index, the array
will be spare. For example:

const fruits = ['Apple', 'Orange', 'Strawberry'];


fruits.length = 5;

console.log(fruits); // [ 'Apple', 'Orange', 'Strawberry', <2 empty items> ]

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.

Introduction to the JavaScript Array push() method


The Array.prototype.push() method adds one or more elements to the end of an array and returns
the new array’s length.

The following shows the syntax of the push() method:

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.

JavaScript Array push() method examples


Let’s take some examples of using the push() method.

1) Using the array push() to append one element to an array


The following example adds the number 40 to the end of the numbers array:

let numbers = [10, 20, 30];

const length = numbers.push(40);

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:

let numbers = [10, 20, 30];

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:

const length = numbers.push(40);

Third, output the length variable and the numbers array:

console.log(length);
console.log(numbers);

The following picture illustrates how the example works:

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:

let numbers = [10, 20, 30];

const length = numbers.push(40, 50);

console.log(length);
console.log(numbers);

Output:

5
[ 10, 20, 30, 40, 50 ]

The following picture illustrates how it works:


fi
3) Using the push() to append elements of an array to another array
Suppose you have two arrays colors and cmyk:

let colors = ['red', 'green', 'blue'];


let cmyk = ['cyan', 'magenta', 'yellow', 'back'];

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:

let colors = ['red', 'green', 'blue'];


let cmyk = ['cyan', 'magenta', 'yellow', 'back'];

for (const color of cmyk) {


colors.push(color);
}

console.log(colors);

Output:

['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'back']

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:

let colors = ['red', 'green', 'blue'];


let cmyk = ['cyan', 'magenta', 'yellow', 'back'];

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.

See the following example:

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.

Third, output the greetings object to the console:

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.

Introduction to the JavaScript Array unshift() method


The Array.prototype.unshift() method adds one or more elements to the beginning of an array and
returns the new array’s length.

The following shows the syntax of the unshift() method:

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.

JavaScript Array unshift() method examples


Let’s take some examples of using the unshift() method.

1) Using the JavaScript Array unshift() method to prepend an element to an array


The following example uses the unshift() method to add the number 10 to the numbers array:

let numbers = [30, 40];

const length = numbers.unshift(20);

console.log({ length });


console.log({ numbers });

Output:

{ length: 3 }
{ numbers: [ 20, 30, 40 ] }
How it works.
First, de ne an array that has two elements:

let numbers = [20, 30];

The length of the numbers array is 2.


Second, add the number 10 to the beginning of the numbers array and assign the new
array’s length to the length variable:

const length = numbers.unshift(10);

Third, output the length and numbers variables to the console:

console.log({ length });


console.log({ numbers });

The following picture illustrates how the unshift() function works:

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:

let numbers = [30, 40];

const length = numbers.unshift(10, 20);

console.log({ length });


console.log({ numbers });

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:

let days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];


let weekends = ['Sat', 'Sun'];

for (const weekend of weekends) {


days.unshift(weekend);
}

console.log(days);

Output:

['Sun', 'Sat', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Starting from ES6, you can use the spread operator to make the code more concise, like this:

let days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];


let weekends = ['Sat', 'Sun'];

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;
},
};

greetings.prepend('Good day', 'Bye');

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.

Introduction to the JavaScript Array pop() method


The Array.prototype.pop() method removes the last element from an array and returns the
removed element. Here’s the syntax of the pop() method:

array.pop()

The pop() method changes the length property of the array. If the array is empty,
the pop() returns unde ned.

JavaScript pop() method example


Let’s take some examples of using the pop() method.

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:

const numbers = [10, 20, 30];


const last = numbers.pop();

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:

const numbers = [];


const last = numbers.pop();

console.log(last);
console.log(numbers.length);

Output:

unde ned
0

Using JavaScript pop() method with array-like objects


The pop() method is generic. Therefore, you can use the call() or apply() to call the pop() method
on the array-like object. Internally, the pop() uses the length property of the array-like object to
determine the last element to remove.

See the following example:

let greetings = {
0: 'Hi',
1: 'Hello',
2: 'Howdy',
length: 2,
removeLast() {
return [].pop.call(this);
},
};

let greting = greetings.removeLast();

console.log(greting);
console.log(greetings);

Output:

'Howdy'

{
'0': 'Hi',
'1': 'Hello',
length: 2,
removeLast: [Function: removeLast]
}
fi
fi
How it works.

First, de ne the greetings object that has:

• Four properties 0, 1, 2, and length.


• One method removeLast() that uses the call() method of an array to invoke the pop() method.
Second, call the removeLast() method of the greetings object:

let greting = greetings.removeLast();

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.

Introduction to the JavaScript Array shift() function


The Array.prototype.shift() method removes the rst element from an array and returns that
element. The following shows the syntax of the shift() method:

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.

JavaScript Array shift() method examples


Let’s take some examples of using the shift() method.

1) Using the JavaScript array shift() method example


The following example uses the shift() method to remove the rst element from an array:

const numbers = [10, 20, 30];


let number = numbers.shift();

console.log({ number });


console.log({ numbers });
console.log({ length: numbers.length });

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:

const numbers = [10, 20, 30];

Second, remove the rst element from the numbers array and assign the removed element to
the number variable.

let number = numbers.shift();

Third, output the removed element, array, and the array’s length to the console:

console.log({ number });


console.log({ numbers });
console.log({ length: numbers.length });

The following picture illustrates how the above example works:

2) Using the JavaScript array shift() method example


The following example shows how to use the shift() method with a while loop to remove all
elements of an array:

const numbers = [10, 20, 30];


let number;
while ((number = numbers.shift()) != unde ned) {
console.log(number);
}

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);
},
};

const greeting = greetings.removeFirst();

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:

const greeting = greetings.removeFirst();

Third, output the greeting and greetings to the console:

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.

Deleting elements using JavaScript Array’s splice() method


To delete elements in an array, you pass two arguments into the splice() method as follows:

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.

Let’s take a look at the following example.

Suppose, you have an array scores that contains ve numbers from 1 to 5.

let scores = [1, 2, 3, 4, 5];

The following statement deletes three elements of the scores array starting from the rst element.

let deletedScores = scores.splice(0, 3);

The scores array now contains two elements.

console.log(scores); // [4, 5]

And the deletedScores array contains three elements.

console.log(deletedScores); // [1, 2, 3]
fi
fi
fi
fi
The following gure illustrates the scores.splice(0,3) method call above.

Inserting elements using JavaScript Array splice() method


You can insert one or more elements into an array by passing three or more arguments to
the splice() method with the second argument is zero.
Consider the following syntax.

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.

let colors = ['red', 'green', 'blue'];

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.

console.log(colors); // ["red", "green", "purple", "blue"]


fi
fi
The following gure demonstrates the method call above.

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.

colors.splice(1, 0, 'yellow', 'pink');


console.log(colors);
// ["red", "yellow", "pink", "green", "purple", "blue"]

Replacing elements using JavaScript Array splice() method


The splice() method allows you to insert new elements into an array while deleting existing
elements simultaneously.
To do this, you pass at least three arguments with the second one that speci es the number
of items to delete and the third one that indicates the elements to insert.
Note that the number of elements to delete needs not to be the same as the number of
elements to insert.
Suppose you have an array of programming languages with four elements as follows:

let languages = ['C', 'C++', 'Java', 'JavaScript'];

The following statement replaces the second element by a new one.

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.

console.log(languages); // ["C", "Python", "C#", "Swift", "Go", "JavaScript"]

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.

Introduction to JavaScript Array slice() method


The slice() method accepts two optional parameters as follows:

slice(start, stop);

Both start and stop parameters are optional.

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:

var numbers = [1,2,3,4,5];


var newNumbers = numbers.slice();

In this example, the newNumbers array contains all the elements of the numbers array.

Copy a portion of an array


The typical use of the slice() method is to copy a portion of an array without modifying the source
array. Here is an example:

var colors = ['red','green','blue','yellow','purple'];


var rgb = colors.slice(0,3);
console.log(rgb); // ["red", "green", "blue"]

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);
}

var classi cation = toArray('A','B','C');

console.log(classi cation); // ["A", "B", "C"]

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.

Sometimes, you see the following syntax:

var list = [].slice.call(document.querySelectorAll('p'));

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.

Introduction to the JavaScript array indexOf() method


To nd the position of an element in an array, you use the indexOf() method. This method returns
the index of the rst occurrence the element that you want to nd, or -1 if the element is not found.

The following illustrates the syntax of the indexOf() method.

Array.indexOf(searchElement, fromIndex)

As shown above, the indexOf() method accepts two named arguments.

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 JavaScript array indexOf() method examples


Suppose, you have an array scores that consists of six numbers as follows:

var scores = [10, 20, 30, 10, 40, 20];

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:

console.log(scores.indexOf(20,-1)); // 5 (fromIndex = 6+ (-1) = 5)


console.log(scores.indexOf(20,-5)); // 1 (fromIndex = 6+ (-5) = 1)

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.

function nd(needle, haystack) {


var results = [];
var idx = haystack.indexOf(needle);
while (idx != -1) {
results.push(idx);
idx = haystack.indexOf(needle, idx + 1);
}
return results;
}
fi
fi
fi
fi
The following example uses the nd() function above to return an array of positions of the number
10 in the scores array.

console.log( nd(10,scores)); // [0, 3]

JavaScript array lastIndexOf() method


The Array type has another method called lastIndexOf() that provides the similar functionality to
the indexOf() method.

The following illustrates the syntax of the lastIndexOf() method:

Array.lastIndexOf(searchElement[, fromIndex = Array.length - 1])

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.

Introduction to the JavaScript Array includes() method


When working with an array, you often want to check if the array contains an element. To do
this, you use the indexOf() method as follows:

let numbers = [1,2,3];


if(numbers.indexOf(2) !== -1){
// process here
}

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.

ECMAScript 2016 standardized this functionality by providing the Array.prototype.includes() method.

The includes() method returns true if an array contains a given element; Otherwise, it returns false.

The following illustrates the syntax of the includes() method:

array.includes(element,fromIndex);

The includes() accepts two arguments:


• The rst argument is the element that can be searched.
• The fromIndex is the position in the array to which the search starts.
fi
fi
See the following example:

[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.

let bmw = {name: 'BMW' },


toyota = { name: 'Toyota'},
ford = {name: 'Ford'}

let cars = [ford, toyota];

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.

Introduction to the Array nd() method


In ES5, to nd an element in an array, you use the indexOf() or lastIndexOf() methods. However,
these methods are quite limited because they return the index of the rst matching element only.

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:

nd(callback(element[, index[, array]])[, thisArg])

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:

let numbers = [1, 2, 3, 4, 5];

console.log(numbers. nd(e => e % 2 == 0));

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.

console.log(customers. nd(c => c.credit > 100));

Output:

{ name: 'ACME Corp', credit: 200 }

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.

Introduction to the JavaScript Array ndIndex() Method


ES6 added a new method called ndIndex() to the Array.prototype, which allows you to nd
the rst element in an array that satis es a provided testing function.
The ndIndex() method returns the index of the element that satis es a testing function or -1
if no element passed the test.
The following illustrates the syntax of the ndIndex() method:

ndIndex(testFn(element[, index[, array]])[, thisArg])

The ndIndex() takes two arguments:

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.

1) Using the Array ndIndex() method with a simple array example


The following example returns the index of the rst occurrence of the number 7 in the ranks array:

let ranks = [1, 5, 7, 8, 10, 7];


let index = ranks. ndIndex(rank => rank === 7);
console.log(index);

Output:

2) Using the Array ndIndex() method with a more complex condition


This example uses the ndIndex() method to get the index of the rst occurrence of the number 7
after the index 2 in the ranks array:

let ranks = [1, 5, 7, 8, 10, 7];

let index = ranks. ndIndex(


(rank, index) => rank === 7 && index > 2
);

console.log(index);

Output:

3) Using the Array ndIndex() method with an array of objects


The following example uses the Array ndIndex() method to nd the index of the rst product
whose price is greater than 1000:

const products = [
{ name: 'Phone', price: 999 },
{ name: 'Computer', price: 1999 },
{ name: 'Tablet', price: 995 },
];

const index = products. ndIndex(product => product.price > 1000);

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.

Introduction to JavaScript Array map() method


Sometimes, you need to take an array, transform its elements, and include the results in a new array.

Typically, you use a for loop to iterate over the elements, transform each individual one, and push the
results into a new array.

Let’s take a look at an example.

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.

let areas = []; // to store areas of circles


let area = 0;
for (let i = 0; i < circles.length; i++) {
area = Math. oor(Math.PI * circles[i] * circles[i]);
areas.push(area);
}
console.log(areas);

Output

It takes a quite amount of code to accomplish this.

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

[314, 2827, 7853]

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.

let areas = circles.map(function(radius){


return Math. oor(Math.PI * radius * radius);
});
console.log(areas);

Also, you can make use of the arrow function in ES6 to achieve the same result with a cleaner code:

let areas = circles.map(radius => Math. oor(Math.PI * radius * radius));


console.log(areas);

JavaScript Array map() method in detail


The following illustrates the map() method.

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){
// ...
}

The callback() function takes three arguments:


• The currentElement is the current element of the array that is being processed.
• The index is the index of the currentElement.
• The array is the array object being traversed.
The currentElement is required while the index and array arguments are optional.
If you pass the contextObject to the map() method, you can reference
the contextObject inside the callback() function using the this keyword.
It’s important to note that the map() method does not change the original array, it creates a
new array of all elements that have been transformed by the callback function.

More JavaScript Array map() examples


The following example shows how to transform an array of numbers by using a built-in method of
the Math type as the callback() function.

let numbers = [16, 25, 36];


let results = numbers.map(Math.sqrt);
console.log(results);

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.

Introduction to JavaScript array lter() method


One of the most common tasks when working with an array is to create a new array that contains a
subset of elements of the original 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:

let bigCities = [];


for (let i = 0; i < cities.length; i++) {
if (cities[i].population > 3000000) {
bigCities.push(cities[i]);
}
}
console.log(bigCities);

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:

let bigCities = cities. lter(function (e) {


return e.population > 3000000;
});
console.log(bigCities);

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:

let bigCities = cities. lter(city => city.population > 3000000);

console.log(bigCities);

JavaScript Array lter() method in detail


The following illustrates the syntax of the lter() method:

arrayObject. lter(callback, contextObject);

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.

Like other iterative methods of the Array object such


as every(), some(), map() and forEach(), the callback function has the following form:

function callback(currentElement, index, array){


// ...
}
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
The callback function takes three arguments:
• The currentElement argument is the current element in the array that is being
processed by the callback function.
• The index of the currentElement that is being processed by the callback function.
• The array object being traversed.
The index and array arguments are optional.
The contexObject argument of the lter() method is optional. If you pass the this value, you
can reference it by using this keyword inside the callback function.
It is important to note that the lter() method does not change the original array.

More JavaScript Array lter() method examples


Because the lter() method returns a new array, you can chain the result with other array methods
such as sort() and map().

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
};

let numberInRange = data. lter(isInRange, range);

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.

Introduction to the JavaScript Array reduce() method


Suppose that you have an array of numbers, like this:

let numbers = [1, 2, 3];

and you want to calculate the total of elements of the array.

Typically, you use a for loop to iterate over the elements and add them up as shown in the following example:

let numbers = [1, 2, 3];

let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}

console.log(sum);

Output:

The script is simple and straightforward:

• First, declare an array of three numbers 1, 2 and 3.


• Second, declare the sum variable and set its value to zero.
• Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop,
the value of the sum variable is 6.
What we have done was to reduce an array into a value.

The Array.prototype allows you to reduce an array to a single value using the reduce() method like this:

let numbers = [1, 2, 3];


let sum = numbers.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
});

console.log(sum);
It’s pretty simple, isn’t it?
Let’s take a look at the reduce() method in detail.

JavaScript Array reduce() method in detail


The following illustrates the syntax of the reduce() method:

array.reduce(callbackFn [, initialValue])

The reduce() method takes two arguments:

• A callback function callbackFn. The function is often referred to as a reducer.


• An optional initial value.
The reduce() method calls the callbackFn() function for every element in the array.

The reducer() function returns a value that results from executing the callbackFn to completion over
the entire array.

1) The callbackFn() function argument


The callbackFn function has the following syntax:

function callbackFn(previousValue, currentValue, currentIndex, array) { /**/}

The callbackFn function takes four arguments:

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

The array to loop through.


fi
fi
fi
2) The initialValue argument
The initialValue argument is optional.

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:

initialValue previousValue currentValue


passed initialValue array[0]
not passed array[0] array[1]

The following example shows the progress of the reduce() function with an initialValue as 100:

let numbers = [1, 2, 3];

function getOrdinalSu x(i) {


let j = i % 10, k = i % 100;
if (j == 1 && k != 11) return i + 'st';
if (j == 2 && k != 12) return i + 'nd';
if (j == 3 && k != 13) return i + 'rd';
return i + 'th';
}

let call = 1;
let sum = numbers.reduce(function (previousValue, currentValue, currentIndex, array) {
let result = previousValue + currentValue;

// show the 1st call, 2nd call, etc.


console.log(`${getOrdinalSu x(call)} call`);
call++;

// show the immediate values


console.table({ previousValue, currentValue, currentIndex, result });

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:

let total = shoppingCart.reduce(function (previousValue, currentValue) {


return previousValue + currentValue.qty * currentValue.price;
}, 0);

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.

See the following example:

let numbers = [1, 2, 3];

let sum = numbers.reduceRight(function (previousValue, currentValue) {


console.log({ previousValue, currentValue });
return previousValue + currentValue;
});

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.

Checking array elements using the for loop


Sometimes, you need to test whether every element of an array satis es a speci ed condition.

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:

let numbers = [1, 3, 5];

The following code checks if every element in the numbers array is greater than zero:

let numbers = [1, 3, 5];


let result = true;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
result = false;
break;
}
}
console.log(result);

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:

let numbers = [1, 3, 5];


let result = numbers.every(function (e) {
return e > 0;
});

console.log(result);

Output:

true

By using the ES6 arrow functions, the code can be even shorter:

let numbers = [1, 3, 5];

let result = numbers.every( e => e > 0);

console.log(result);

It is also much cleaner, isn’t it?


The following illustrates the syntax of the every() method.

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:

function callback(currentElement, index, array){


//...
}

The callback() function takes three arguments:

• First, the currentElement is the current element that is being processed.


• Second, the index is the index of the currentElement.
• Third, the array is the array that the every() method was called upon.
The currentElement argument is required whereas the index and array arguments are optional.

2) The thisArg argument


The thisArg argument of the every() method is optional. If you pass the thisArg argument into
the method, the this value inside the callback function will reference the thisArg argument.
The every() method returns true if the callback function returns a truthy value for every array
element; otherwise, it returns false.
Note that the every() method executes the callback() function on every element in the array
until it nds the one that causes the callback() return a falsy value.
In other words, the every() will stop calling the callback() function and return false once there
is an array element that causes callback() to return a falsy value.
Let’s take a look at some more examples of using the every() method.

More JavaScript Array every() method examples


The following example tests whether all the array elements are the even numbers

let numbers = [1, 3, 5];


let isEven = numbers.every(function (e) {
return e % 2 == 0;
});

console.log(isEven);

Output:

false
fi
In contrast, the following example tests if all the array elements are the odd numbers.

let numbers = [1, 3, 5];

let isOdd = numbers.every(function (e) {


return Math.abs(e % 2) == 1;
});

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 numbers = [1, 3, 5];

let range = {
min: 0,
max: 10
};

let isInRange = numbers.every(function (e) {


return e >= this.min && e <= this.max;
}, range);

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:

let gtZero = [].every(e => e > 0); // any condition


let ltZero = [].every(e => e < 0); // any condition

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.

Introduction to the JavaScript Array some() method


Sometimes, you want to check if an array has at least one element that meets a speci ed
condition.
For example, to check if the following array has at least one element less than 5:

let marks = [ 4, 5, 7, 9, 10, 3 ];

…you typically use a for loop, like this:

let marks = [ 4, 5, 7, 9, 10, 3 ];

let lessThanFive = false;

for (let index = 0; index < marks.length; index++) {


if (marks[index] < 5) {
lessThanFive = true;
break;
}
}

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:

let marks = [ 4, 5, 7, 9, 10, 3 ];

let lessThanFive = marks.some(e => e < 5);

console.log(lessThanFive);

JavaScript Array some() syntax


The following illustrates the syntax of the some() method:

arrayObject.some(callback[, thisArg]);

The some() method accepts two arguments:

1) The callback argument


The some() function executes the callback function once for each element in the array until it nds
the one where the callback function returns a true. The some() method immediately
returns true and doesn’t evaluate the remaining elements.

If no element causes the callback() to return true, the some() method returns false.

The callback function takes three arguments:

function callback(currentElement [[, currentIndex], array]){ // ...}


fi
• The currentElement is the current element being processed in the array.
• The currentIndex is the index of the current element being processed in the array.
• The array is array that some() was called upon.

2) The thisArg argument


The thisArg argument is optional. If you pass the thisArg into the method, you can use the thisArg as
the this value inside the callback function.

JavaScript Array some() examples


Let’s take some more examples of using the some() method.

1) Check if an element exists in the array


The following exists() function uses the some() method to check if a value exists in an array:

function exists(value, array) {


return array.some(e => e === value);
}

let marks = [4, 5, 7, 9, 10, 2];

console.log(exists(4, marks));
console.log(exists(11, marks));

Output:

true
false

2) Check if an array has one element that is in a range


The following example shows how to check if any number in the marks array is in the range of (8, 10):

let marks = [4, 5, 7, 9, 10, 2];


const range = {
min: 8,
max: 10
};
let result = marks.some(function (e) {
return e >= this.min && e <= this.max;
}, range);

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.

Caution: Empty arrays


If you call the some() method on an empty array, the result is always false regardless of any
condition. For example:

let result = [].some(e => e > 0);


console.log(result);

result = [].some(e => e <= 0);


console.log(result);

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.

Introduction to JavaScript Array sort() method


The sort() method allows you to sort elements of an array in place. Besides returning the sorted
array, the sort() method changes the positions of the elements in the original array.

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.

Consider the following example:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];


numbers.sort();
console.log(numbers);

The output is:

[ 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.

The following illustrates the syntax of the sort() method:

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:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];


numbers.sort( function( a , b){
if(a > b) return 1;
if(a < b) return -1;
return 0;
});

console.log(numbers);

Output:

[ 0, 1, 2, 3, 10, 20, 30 ]

Or you can de ne the comparison function using the arrow function syntax:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];


numbers.sort((a,b) => {
if(a > b) return 1;
if(a < b) return -1;
return 0;
});

console.log(numbers);

And the following is the simplest since the elements of the array are numbers:

let numbers = [0, 1, 2, 3, 10, 20, 30];


numbers.sort((a, b) => a - b);

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:

[ 'ant', 'bee', 'cat', 'dog', 'elephant' ]

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:

[ 'elephant', 'dog', 'cat', 'bee', 'ant' ]


Suppose you have an array that contains elements in both uppercase and lowercase as follows:

// sorting array with mixed cases


let mixedCaseAnimals = [
'Cat', 'dog', 'Elephant', 'bee', 'ant'
];

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:

[ 'ant', 'bee', 'Cat', 'dog', 'Elephant' ]

Sorting an array of strings with non-ASCII characters


The sort() method is working ne with the strings with ASCII characters. However, for the strings
with non-ASCII characters e.g., é, è, etc., the sort() method will not work correctly. For example:

let animaux = ['zèbre', 'abeille', 'écureuil', 'chat'];


animaux.sort();

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:

[ 'abeille', 'chat', 'écureuil', 'zèbre' ]

The elements of the animaux array now are in the correct order.

Sorting an array of numbers


Suppose you have an array of numbers named scores as in the following example.

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:

[ 5, 9, 10, 20, 70, 80 ]

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:

[80, 70, 20, 10, 9, 5]

Sorting an array of objects by a speci ed property


The following is an array of employee objects, where each object contains three properties: name,salary and hireDate.

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"}
];

Sorting objects by a numeric property


The following example shows how to sort the employees by salary in ascending order.

// 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);

Sorting objects by the date property


Suppose, you wish to sort employees based on each employee’s hire date.
The hire date data is stored in the hireDate property of the employee object. However, it is
just a string that represents a valid date, not the Date object.
Therefore, to sort employees by hire date, you rst have to create a valid Date object from
the date string, and then compare two dates, which is the same as comparing two numbers.
Here is the solution:

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.

See the following example:

let rivers = ['Nile', 'Amazon', 'Congo', 'Mississippi', 'Rio-Grande'];

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:

// temporary array holds objects with position


// and length of element
var lengths = rivers.map(function (e, i) {
return {index: i, value: e.length };
});

// sorting the lengths array containing the lengths of


// river names
lengths.sort(function (a, b) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// copy element back to the array


var sortedRivers = lengths.map(function (e) {
return rivers[e.index];
});

console.log(sortedRivers);

Output:

[ 'Nile', 'Congo', 'Amazon', 'Rio-Grande', 'Mississippi' ]

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.

Introduction to JavaScript Array forEach() method


Typically, when you want to execute a function on every element of an array, you use
a for loop statement.
For example, the following code shows every element of an array to console:

let ranks = ['A', 'B', 'C'];


for (let i = 0; i < ranks.length; i++) {
console.log(ranks[i]);
}

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:

let ranks = ['A', 'B', 'C'];

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.

The following illustrates the syntax of the forEach() method.

Array.forEach(callback [, thisArg]);

The forEach() method takes two arguments:

1) callback
The callback function that the forEach() method uses to execute on every element.

The callback accepts the following arguments:

• currentElement: is the current array element being processed.


• index: the index of the currentElement in the array.
• array: the array that calls the forEach() method.
The index and array are optional.

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.

More JavaScript Array forEach() method example


Let’s take a look at an example of the forEach() method that uses a contextObject.

The following illustrates Counter constructor 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.

var counter = new Counter();


var numbers = [1, 2, 3];
var sum = 0;
numbers.forEach(function (e) {
sum += e;
this.increase();
}, counter);

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:

let odds = [1,3,5];


let evens = [2,4,6];
// merge odds and evens array
let combined = odds.concat(evens);

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 ([]):

let odds = [1,3,5];


let evens = [2,4,6];
// merge odds and evens array
let combined = [].concat(odds, evens);

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:

let upper = ['A','B','C'];


let lower = ['a','b','c'];
let digits = [1,2,3];
let alphanumerics = upper.concat(lower, digits);

Output:

['A', 'B', 'C', 'a', 'b', 'c', 1, 2, 3]

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:

let colors = ['red','green','blue'];


let rgb = colors.concat();
console.log(rgb);

Output:

[ 'red', 'green', 'blue' ]

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:

let rgb = ['red','green','blue'];


let moreColors = rgb.concat('yellow','magento');
console.log(moreColors);

Output:

[ 'red', 'green', 'blue', 'yellow', 'magento' ]

In ES6, you can use spread operator to merge multiple arrays as follows:

let odds = [1,3,5];


let evens = [2,4,6];
let combined = [...odds, ...evens];
console.log(combined);

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.

Introduction to the JavaScript Array.of() method


In ES5, when you pass a number to the Array constructor, JavaScript creates an array whose
length equals the number. For example:

let numbers = new Array(2);


console.log(numbers.length); // 2
console.log(numbers[0]); // unde ned

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:

numbers = new Array("2");


console.log(numbers.length); // 1
console.log(numbers[0]); // "2"

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:

Array.of(element0[, element1[, ...[, elementN]]])


fi
JavaScript Array.of() examples
See the following example:

let numbers = Array.of(3);


console.log(numbers.length); // 1
console.log(numbers[0]); // 3

In this example, we passed the number 3 to the Array.of() method. The Array.of() method creates
an array of one number.

Consider the following example:

let chars = Array.of('A', 'B', 'C');


console.log(chars.length); // 3
console.log(chars); // ['A','B','C']

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.

JavaScript Array.of() poly ll


If you execute the JavaScript in the environment that doesn’t support the Array.of() method,
you can use the following poly ll:

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.

Introduction to JavaScript Array Array.from() method


To create an array from an array-like object in ES5, you iterate over all array elements and
add each of them to an intermediate array like this:

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:

[ 'Apple', 'Orange', 'Banana' ]

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:

Array.from(target [, mapFn[, thisArg]])

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.

A) Create an array from an array-like object


The following example uses the Array.from() method to create a new array from the arguments object of a
function:

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.

B) JavaScript Array Array.from() with a mapping function


The Array.from() method accepts a callback function that allows you to execute the mapping
function on every element of the array which is being created. See the following example:

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 ]

D) Create an array from an iterable object


Since the Array.from() method also works on an iterable object, you can use it to create an array
from any object that has a [symbol.iterator] property. For example:

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.

Introduction to the JavaScript Array at() method


ES2019 introduced the Array.prototype. at() method that creates a new array with all the elements
of the subarrays concatenated to it recursively up to a speci ed depth.

The following shows the syntax of the at() method:

let newArray = arrayObject. at([depth])

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:

const numbers = [1, 2, [3, 4, 5]];


const atNumbers = numbers. at();

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:

const numbers = [1, 2, [3, 4, 5, [6, 7]]];


const atNumbers = numbers. at(2);

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:

const numbers = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];


const atNumbers = numbers. at(In nity);

console.log( atNumbers);

If an array has empty slots, you can use the at() method to remove the holes, like this:

const numbers = [1, 2, , 4, , 5];


const sequence = numbers. at();

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.

Introduction to JavaScript Array atMap() method


The at() method creates a new array with the elements of the subarrays concatenated into it.

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.

The following shows the syntax of the atMap() method:

let newArray = arrayObject. atMap(callback,thisArg);

The atMap() method takes two parameters:

1) The callback mapping function


The callback is the mapping function has the same syntax as the one in the map() method:

function callback(currentValue [[,index], array]);

2) The thisArg argument


The optional thisArg argument is a value to use as this when executing the callback.
Note that the atMap() method doesn’t modify the original array.
fl
fl
fl
fl
fl
fl
fi
fl
fl
fl
fl
fl
fl
fl
JavaScript Array atMap() examples
Let’s take some examples of using the atMap() method.

1) Creating words from sentences example


Suppose that you have the following array:

let sentences = ["JavaScript Array atMap()", " ", "is", " ", "Awesome"];

The following map() function splits the words of sentences:

let words = sentences.map(s => s.split(' '));


console.log(words);

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:

Suppose that you have the following shopping cart:

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:

let newCart = cart. atMap(


(item) => {
if (item.name === 'Smartphone') {
return [item, {
name: 'Screen Protector',
qty: item.qty,
price: 5,
freeOfCharge: true
}]
} else {
return [item];
}
}
);

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:

const total = newCart.reduce((sum, item) => {


if (!item.freeOfCharge)
sum += item.price * item.qty;
return sum;
}, 0);

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.

Introduction to the JavaScript array join() method


The join() method allows you to concatenate all elements of an array and returns a new string:

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.

JavaScript Array join() method examples


Let’s take some examples of using the join() method.

1) Using the JavaScript Array join() method to join CSS classes


The following example uses the JavaScript Array join() method to join CSS classes:

const cssClasses = ['btn', 'btn-primary', 'btn-active'];


const btnClass = cssClasses.join(' ');

console.log(btnClass);

Output:

btn btn-primary btn-active


fi
In this example, we have an array that holds a list of CSS classes. And we use the join() method joins all
elements of the cssClasses array and return a string of the CSS classes separated by a space.

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 (-):

const title = 'JavaScript array join example';


const url = title.split(' ')
.join('-')
.toLowerCase();

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.

Introduction to JavaScript Array destructuring


Assuming that you have a function that returns an array of numbers as follows:

function getScores() {
return [70, 80, 90];
}

The following invokes the getScores() function and assigns the returned value to a variable:

let scores = getScores();

To get the individual score, you need to do like this:

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:

let [x, y, z] = getScores();

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];
}

let [x, y, z] = getScores();

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];
}

let [x, y, z] = getScores();

console.log(x); // 70
console.log(y); // 80
console.log(z); // 90

Array Destructuring Assignment and Rest syntax


It’s possible to take all remaining elements of an array and put them in a new array by using
the rest syntax (…):

let [x, y ,...args] = getScores();


console.log(x); // 70
console.log(y); // 80
console.log(args); // [90, 100]

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

Setting default values


See the following example:

function getItems() {
return [10, 20];
}

let items = getItems();


let thirdItem = items[2] != unde ned ? items[2] : 0;

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:

let [, , thirdItem = 0] = getItems();

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;
}

let [a = 10, b = 20] = getItems() || [];

console.log(a); // 10
console.log(b); // 20

Nested array destructuring


The following function returns an array that contains an element which is another array, or nested array:

function getPro le() {


return [
'John',
'Doe',
['Red', 'Green', 'Blue']
];
}

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:

let [ rstName, lastName,


[
color1, color2, color3
]
] = getPro le();

console.log(color1, color2, color3); // Red Green Blue


fi
fi
fi
Array Destructuring Assignment Applications
Let’s see some practical examples of using the array destructuring assignment syntax.

1) Swapping variables
The array destructuring makes it easy to swap values of variables without using a temporary variable:

let a = 10,
b = 20;

[a, b] = [b, a];

console.log(a); // 20
console.log(b); // 10

2) Functions that return multiple values


In JavaScript, a function can return a value. However, you can return an array that contains
multiple values, for example:

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:

let [sum, average, di erence] = stat(20, 10);


console.log(sum, average, di erence); // 30, 15, 10

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.

Introduction to the JavaScript spread operator


ES6 provides a new operator called spread operator that consists of three dots (...). The spread
operator allows you to spread out elements of an iterable object such as an array, map, or set. For
example:

const odd = [1,3,5];


const combined = [2,4,6, ...odd];
console.log(combined);

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.

function f(a, b, ...args) {


console.log(args);
}

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:

const odd = [1,3,5];


const combined = [...odd, 2,4,6];
console.log(combined);

Output:

[ 1, 3, 5, 2, 4, 6 ]

Or

const odd = [1,3,5];


const combined = [2,...odd, 4,6];
console.log(combined);

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.

JavaScript spread operator and apply() method


See the following compare() function compares two numbers:

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:

let result = compare.apply(null, [1, 2]);


console.log(result); // -1
However, by using the spread operator, you can pass an array of two numbers to the compare() function:

let result = compare(...[1, 2]);


console.log(result); // -1

The spread operator spreads out the elements of the array so a is 1 and b is 2 in this case.

A better way to use the Array’s push() method example


Sometimes, a function may accept an inde nite number of arguments. Filling arguments from an array is
not convenient.

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:

let rivers = ['Nile', 'Ganges', 'Yangte'];


let moreRivers = ['Danube', 'Amazon'];

[].push.apply(rivers, moreRivers);
console.log(rivers);

This solution looks verbose.


The following example uses the spread operator to improve the readability of the code:

rivers.push(...moreRivers);

As you can see, using the spread operator is much cleaner.

JavaScript spread operator and array manipulation


1) Constructing array literal
The spread operator allows you to insert another array into the initialized array when you
construct an array using the literal form. See the following example:

let initialChars = ['A', 'B'];


let chars = [...initialChars, 'C', 'D'];
console.log(chars); // ["A", "B", "C", "D"]

2) Concatenating arrays
Also, you can use the spread operator to concatenate two or more arrays:

let numbers = [1, 2];


let moreNumbers = [3, 4];
let allNumbers = [...numbers, ...moreNumbers];
console.log(allNumbers); // [1, 2, 3, 4]
fi
3) Copying an array
In addition, you can copy an array instance by using the spread operator:

let scores = [80, 70, 90];


let copiedScores = [...scores];
console.log(copiedScores); // [80, 70, 90]

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.

JavaScript spread operator and strings


Consider the following example:

let chars = ['A', ...'BC', 'D'];


console.log(chars); // ["A", "B", "C", "D"]

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.

Introduction to the JavaScript Array at() method


In JavaScript, you can use the square bracket [] to access an element of an array. For example,
the arr[0] returns the rst element in the array arr, the arr[1] returns the second element, and so on.

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:

const scores = [5, 6, 7];

console.log(scores.at(1)); // same as scores[1]

// get the last element


console.log(scores.at(-1)); // 7

console.log(scores.at(-1) === scores[scores.length - 1]); // true

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.

Introduction to JavaScript multidimensional array


JavaScript does not provide the multidimensional array natively. However, you can create a
multidimensional array by de ning an array of elements, where each element is also another array.

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 = [];

The following example de nes a two-dimensional array named activities:

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

Adding elements to the JavaScript multidimensional array


You can use the Array methods such as push() and splice() to manipulate elements of a multidimensional array.

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:

activities.splice(1, 0, ['Programming', 2]);


console.table(activities);
fi
fi
Here is the output:

(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);

The following shows the output in the console:


(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%'
6 Study' 2 8%'
Removing elements from the JavaScript multidimensional array
To remove an element from an array, you use the pop() or splice() method.
For example, the following statement removes the last element of the activities array.

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.

// loop the outer array


for (let i = 0; i < activities.length; i++) {
// get the size of the inner array
var innerArrayLength = activities[i].length;
// loop the inner array
for (let j = 0; j < innerArrayLength; j++) {
console.log('[' + i + ',' + j + '] = ' + activities[i][j]);
}
}

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

Or you can use the forEach() method twice:

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.

You might also like