Home Chapter 7: Arrays.
Post
Cancel

Chapter 7: Arrays.


This chapter documents arrays, a fundamental datatype in JavaScript and in most other programming languages.

Introduction

  • An array is an ordered collection of elements. The elements of an array are stored in a contiguous block of memory. The individual elements are accessed by their position in the array. The position is called the index. The first element of an array is at index 0, the second at index 1, and so on. The last element of an array of length n is at index n-1.
  • Javascript arrays are untyped. This means that the elements of an array can be of any type. The elements of an array can be of different types. The elements of an array can even be arrays themselves. This is called a multidimensional array.
  • Arrays are objects in Javascript. The elements of an array are stored as properties of the array object. The index of an element is the name of the property. The length of an array is the number of elements in the array. The length property of an array is always one more than the highest index of the array.
  • Arrays are mutable. The elements of an array can be changed. The length of an array can be changed. The elements of an array can be added or removed. The length of an array can be set to zero to remove all the elements of an array.
  • Arrays inherit from Array.prototype which provides methods for manipulating arrays. The methods of Array.prototype are available to all arrays.
  • ES6 introduces typed arrays, which are arrays of a single type. The elements of a typed array are stored in a contiguous block of memory, making them more efficient than JavaScript arrays. Unlike JavaScript arrays, typed arrays are not objects and do not inherit from Array.prototype. They also do not have methods, are not resizable, iterable, or mutable. This means that the elements of a typed array cannot be changed once they are assigned. Similarly, the length of a typed array cannot be modified, and elements cannot be added or removed. Setting the length of a typed array to zero does not remove its elements. Typed arrays provide a fixed-size, low-level approach for working with binary data in JavaScript.

Creating Arrays

Using an array literal is the easiest way to create a JavaScript Array.

Simply wrap your elements in square brackets. Don’t forget the comma between each element.

1
2
const fruits = ['Apple', 'Banana']
console.log(fruits.length) // 2

They can also contain objects.

1
2
const fruits = ['Apple', 'Banana', { name: 'Orange' }]
console.log(fruits.length) // 3

If an array literal has multiple commas in a row, with no value between them, the array is sparse. This means that the array has holes in it. The length of a sparse array is greater than the number of elements in the array.

1
2
3
4
5
6
const fruits = ['Apple', , 'Banana']
console.log(fruits.length) // 3

// If an array literal has no elements, but has multiple commas in a row, it is an empty array.
const fruits = [, , ,]
console.log(fruits.length) // 3

Using the Array() constructor to create an array.

You can call it in three different ways:

  • new Array()
  • new Array(length)
  • new Array(element0, element1, ..., elementN)

using the new keyword is optional.

1
2
const fruits = new Array('Apple', 'Banana')
console.log(fruits.length) // 2

If you pass a single number to the Array() constructor, it creates an empty array with the specified length. To create an array with a single element, please consider using array literals or the Array.of() method.

1
2
const fruits = new Array(2)
console.log(fruits.length) // 2

If you pass multiple elements to the Array() constructor, it creates an array with the specified elements.

1
2
const fruits = new Array('Apple', 'Banana')
console.log(fruits.length) // 2

Using the Array.of() method to create an array.

The Array.of() method creates an array with the specified elements.

1
2
const fruits = Array.of('Apple', 'Banana')
console.log(fruits.length) // 2

If you pass a single number to the Array.of() method, it creates an array with the specified number as the only element.

1
2
const x = Array.of(2)
console.log(x.length) // 1

Using the Array.from() method to create an array.

It expects an iterable object as the first argument, and an optional map function as the second argument.

With an iterable object as the first argument, the Array.from() method acts like the spread operator.

1
2
let original = [1, 2, 3]
let copy = Array.from(original)

It helps in making a true array copy from an array-like object. An array-like object is an object that has a length property and indexed elements. Examples of array-like objects are the arguments object, the NodeList returned by methods like document.querySelectorAll(), and strings.

1
2
3
4
5
6
const arrayLike = { length: 2, 0: 'Apple', 1: 'Banana' }
const fruits = Array.from(arrayLike)
console.log(fruits.length) // 2
for (const fruit of fruits) {
  console.log(fruit) // Apple Banana
}

It also accepts a function as the second argument. The function is called for each element in the array and can be used to modify the elements in the array.

1
2
3
4
5
const fruits = Array.from(['Apple', 'Banana'], fruit => fruit.toUpperCase())
console.log(fruits.length) // 2
for (const fruit of fruits) {
  console.log(fruit) // APPLE BANANA
}

Using the spread operator to create an array.

1
2
3
const a = ['Apple', 'Banana']
const b = [...a, 'Orange']
console.log(b.length) // 3

It helps to remember that the spread operator expands an array into its elements, while the rest operator collects multiple elements and condenses them into a single element.

1
2
3
4
5
6
7
8
9
// rest operator
const [a, ...b] = ['Apple', 'Banana', 'Orange']
console.log(a) // Apple
console.log(b) // ['Banana', 'Orange']

// spread operator
const a = ['Apple', 'Banana', 'Orange']
const b = [...a]
console.log(b) // ['Apple', 'Banana', 'Orange']

Reading and Writing Array Elements

Reading an element from an array.

1
2
3
4
const fruits = ['Apple', 'Banana']
console.log(fruits[0]) // Apple
console.log(fruits[1]) // Banana
console.log(fruits[2]) // undefined

Writing an element to an array.

1
2
3
const fruits = ['Apple', 'Banana']
fruits[0] = 'Orange'
console.log(fruits[0]) // Orange

Note that you can index an array using numbers that are negative or that are not integers. When you use such numbers, the array is treated as an object, and the number is treated as a property name. The number is converted to a string, and the array is searched for a property with the same name as the string.

1
2
3
4
const fruits = ['Apple', 'Banana']
fruits[-1] = 'Orange'
console.log(fruits[-1]) // Orange
console.log(fruits['-1']) // Orange

Reading the length of an array.

1
2
const fruits = ['Apple', 'Banana']
console.log(fruits.length) // 2

Writing the length of an array.

If you set the length property to a higher number, the array is extended with undefined elements.

1
2
3
4
const fruits = ['Apple', 'Banana']
fruits.length = 3
console.log(fruits.length) // 3
console.log(fruits[2]) // undefined

If you set the length property to a lower number, the array will be truncated. Truncating an array deletes all elements with an index greater than or equal to the new length.

1
2
3
const fruits = ['Apple', 'Banana']
fruits.length = 0 // remove all elements
console.log(fruits.length) // 0

It is helpful to clearly distinguish an array index from an object property name. An array index is a property name that is a non-negative integer less than 2^32 while all other property names are object property names.

1
2
3
4
const fruits = ['Apple', 'Banana']
fruits['0'] = 'Orange'
console.log(fruits[0]) // Orange
console.log(fruits['0']) // Orange  

Sparse Arrays

An array is sparse if it has holes in it. A hole is an element with an index that is greater than or equal to the length of the array.

1
2
const fruits = ['Apple', , 'Banana']
console.log(fruits.length) // 3

The in operator can be used to check if an array has a hole at a specific index.

1
2
3
4
const fruits = ['Apple', , 'Banana']
console.log(0 in fruits) // true
console.log(1 in fruits) // false
console.log(2 in fruits) // true

Adding and Removing Array Elements

Adding elements to an array.

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

1
2
3
4
const fruits = ['Apple', 'Banana']
const length = fruits.push('Orange')
console.log(length) // 3
console.log(fruits[2]) // Orange

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

1
2
3
4
const fruits = ['Apple', 'Banana']
const length = fruits.unshift('Orange')
console.log(length) // 3
console.log(fruits[0]) // Orange

Removing elements from an array.

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

1
2
3
4
const fruits = ['Apple', 'Banana']
const last = fruits.pop()
console.log(last) // Banana
console.log(fruits.length) // 1

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

1
2
3
4
const fruits = ['Apple', 'Banana']
const first = fruits.shift()
console.log(first) // Apple
console.log(fruits.length) // 1

Deleting elements from an array.

The delete operator removes an element from an array but does not change the length of the array.

1
2
3
4
const fruits = ['Apple', 'Banana']
delete fruits[0]
console.log(fruits.length) // 2
console.log(fruits[0]) // undefined

Splicing an array.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

1
2
3
4
const fruits = ['Apple', 'Banana']
fruits.splice(1, 0, 'Orange') // insert at index 1 (after Apple)
console.log(fruits.length) // 3
console.log(fruits[1]) // Orange

Iterating over Arrays

Iterating over an array.

The for...of loop is the most concise way to iterate over an array.

1
2
3
4
const fruits = ['Apple', 'Banana']
for (const fruit of fruits) {
  console.log(fruit) // Apple Banana
}

If you want to use a for/of loop for an array and need to know the index of each array element, use the entries() method of the array along with destructuring assignment to get the index and value for each iteration.

1
2
3
4
const fruits = ['Apple', 'Banana']
for (const [index, value] of fruits.entries()) {
  console.log(index, value) // 0 Apple, 1 Banana
}

Alternatively, you can use the forEach() method. The forEach() method executes a provided function once for each array element.

1
2
3
4
const fruits = ['Apple', 'Banana']
fruits.forEach((fruit, index, array) => { // the second and third parameters are optional
  console.log(fruit, index) // Apple 0, Banana 1
})

Example 2:

1
2
3
4
5
let arr = Array.of(1 ,2, 3, 4, 5, 6, 7, 8, 9, 10);
arr.forEach((item, index, array) => {
  array[index] = item ** 2; // array[index] = Math.pow(item, 2);
});
console.log(arr); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Reverse iteration.

1
2
3
4
const fruits = ['Apple', 'Banana']
for (let i = fruits.length - 1; i >= 0; i--) {
  console.log(fruits[i]) // Banana Apple
}

The code snippet for (let i = fruits.length - 1; i >= 0; i--) represents a for loop that iterates over an array called fruits in reverse order.

Here’s a breakdown of how the loop works:

  1. Initialization: let i = fruits.length - 1
  • This initializes the loop variable i to the last index of the fruits array. By subtracting 1 from fruits.length, we get the index of the last element in the array.
  1. Condition: i >= 0
  • This specifies the condition for the loop to continue iterating. As long as i is greater than or equal to 0, the loop will execute. This prevents the loop from going beyond the first element (index 0) of the array.
  1. Iteration: i--
  • After each iteration of the loop body, the value of i is decremented by 1. This moves the loop backward through the array.

With this loop structure, the code will execute the loop body for each element of the fruits array, starting from the last element (index fruits.length - 1) and moving towards the first element (index 0).

Iterating over a sparse array.

The examples above assume that the array is dense, that is, it has no holes in it. If the array is sparse, the results of the for…of loop and the forEach() method are different.

1
2
3
4
const fruits = ['Apple', , 'Banana']
for (const fruit of fruits) {
  console.log(fruit) // Apple Banana
}
1
2
3
4
const fruits = ['Apple', , 'Banana']
fruits.forEach((fruit, index) => {
  console.log(fruit, index) // Apple 0, Banana 2
})

To iterate over all elements, including holes, use the for...in loop.

1
2
3
4
const fruits = ['Apple', , 'Banana']
for (const index in fruits) {
  console.log(fruits[index]) // Apple undefined Banana
}

You can also check for undefined using a for loop:

1
2
3
4
5
const data = [1, 2, , , 5]
for(let i = 0; i < data.length; i++) {
    if(data[i] === undefined) continue; //skip undefined
    // rest of the body here
}

Multidimensional arrays

Multidimensional arrays are commonly used to store data in a matrix format (i.e., in rows and columns).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
let array2D = new Array(5);

//Create an array inside every index
for(let i = 0; i < array2D.length; i++) {
  array2D[i] = new Array(5);
}

//Initialize the array
for(let i = 0; i < array2D.length; i++) {
  // loop inner array
  for(let j = 0; j < array2D[i].length; j++) {
    array2D[i][j] = ((i+1)*(j+1)) ** 2;
  }
}

// print the values
for(let i of array2D) {
  let string = "| ";
  for(let j of i) {
    string += `${j.toString().padStart(3)} |`; // Use padStart to ensure the layout is perfect
  }
  console.log(string);
}
/* output
|   1 |  4 |  9 | 16 | 25 |
|   4 | 16 | 36 | 64 |100 |
|   9 | 36 | 81 |144 |225 |
|  16 | 64 |144 |256 |400 |
|  25 |100 |225 |400 |625 |
 */

For a three-dimensional array, you would need three nested loops to iterate over each element in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Implement 3-D arrays => [[[x, y, z], [a,b,c]]]
const array3D = new Array(3); // [,,,,,]

//create the 3D array
for(let i = 0; i < array3D.length; i++) {
  array3D[i] = new Array(3)
  //loop created array
  for(let j = 0; j < array3D[i].length; j++) {
    array3D[i][j] = new Array(3); //New array at 3rd-layer depth
    //loop new array, initialize it :)
    let stringStore = "|"
    for(let val = 0; val < array3D[i][j].length; val++) {
      let indexValue = array3D[i][j][val] = ((i+1) * (j+1) * (val+1)) ** 3; // added 1 to get rid of 0 values in index
      stringStore += `${indexValue.toString().padStart(7)} |` //highest value has a 7 figure
    }
    // Print the values here, formatted
    console.log(stringStore);
  }
}

/* Output ⬇
|      1 |      8 |     27 |
|      8 |     64 |    216 |
|     27 |    216 |    729 |
|      8 |     64 |    216 |
|     64 |    512 |   1728 |
|    216 |   1728 |   5832 |
|     27 |    216 |    729 |
|    216 |   1728 |   5832 |
|    729 |   5832 |  19683 |
*/

Array Methods

Array Iterator Methods

All these methods iterate over arrays by passing array elements in order, to a function you supply and they then provide convenient ways to iterate, map, filter, test and reduce them.

They accept a function as their first argument, and is invoked once for each element of the array. If the array is sparse, the function isn’t invoked for non-existent elements. This function supplied is invoked with three arguments: the value of the array, the index of the element, and the array itself. The latter two are optional.

forEach()

It iterates through an array invoking the function supplied on each element. It returns undefined. It does not mutate the array on which it is called. However, the function it takes as an argument can.

1
2
3
4
5
6
7
8
//Array methods
let arr = [1, 2, 3, 4];

//forEach() method
arr.forEach((value, index, array) => {
    array[index] = value * 100;
});
console.log(arr); // the output is [100, 200, 300, 400]

map()

It works just like the forEach() method, only that it returns a new array and the old array remains unmodified. It is used to transform an array into a new array of the same length, by applying a function to each element.

1
2
3
// map() method. arr is from the previous example.
let arrFromMap = arr.map(value => Math.pow(value, 2));
console.log(arrFromMap); // the output is [10000, 40000, 90000, 160000]

find() and findIndex() methods

  • The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

  • The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

1
2
3
4
// find() and findIndex() methods. arrFromMap is from the previous example.
let find = arrFromMap.find(value => value % 3 === 0);
let findInd = arrFromMap.findIndex(value => Math.sqrt(value) === 400);
console.log(find, findInd); // the output is 90000, 3

filter() method

It creates a new array with all elements that pass the test implemented by the provided function.

1
2
3
4
5
6
//filter()
let sparse = [10, undefined, undefined, 12, 13, 24, 25];
let filtered = sparse.filter(value => value % 2 === 0);
sparse = sparse.filter(value => value !== undefined && value !== null);
console.log(sparse) // the output is [10, 12, 13, 24, 25]
console.log(filtered) // the output is [10, 12, 24]

every() and some() methods

  • The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
  • The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
1
2
3
4
5
//every() method. sparse is from the previous example.
console.log(sparse.every(value => !!value)); // the output is true because all elements are not undefined or null

//some() method
console.log(sparse.some(value => !!value)); // the output is true because some elements are not undefined or null

reduce() and reduceRight() methods

These methods are used to reduce the array to a single value. They iterate over the array and invoke the function you supply on each element, passing in the current value and the element itself. The function is invoked with four arguments: the accumulator, the currentValue, the currentIndex and the array itself.

  • The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
  • The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
1
2
3
4
5
6
7
8
9
10
11
//reduce() and reduceRight() methods. sparse is from the previous example.
let reduced = sparse.reduce(((previousValue, currentValue) => previousValue + currentValue), 0); // the 0 is the initial value of the accumulator
console.log(reduced); // the output is 84

// Get the maximum value in the array
let max = sparse.reduce(((previousValue, currentValue) => previousValue > currentValue ? previousValue : currentValue));
console.log(max); // the output is 25

// When invoked with no initial value, the first element of the array is used as the initial value of the accumulator and skipped as currentValue
let reducedRight = sparse.reduceRight(((previousValue, currentValue) => currentValue ** previousValue)); 
console.log(reducedRight); // the output is 1.6777216e+24

Flattening arrays with flat() and flatMap() methods

flat() method

It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

1
2
3
4
5
6
7
//flat() method
let arr = [1, 2, [3, 4, [5, 6]]];
let flattened = arr.flat();
console.log(flattened); // the output is [1, 2, 3, 4, [5, 6]]

let flattened2 = arr.flat(2);
console.log(flattened2); // the output is [1, 2, 3, 4, 5, 6]

flatMap() method

It first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1.

1
2
3
4
5
6
7
8
9
10
11
//uses of flatMap()
let str = ["Hey there Lucas!", "", "Building something big indeed!"]
let words = str.flatMap(value => value.split(" "));
console.log(words); // the output is ["Hey", "there", "Lucas!", "", "Building", "something", "big", "indeed!"]

let nums = [1, 5, 2, -4, 4];
let altered = nums.flatMap(value => value < 0 ? [] :
    (value % 2 === 0) ? [value] :
        [value - 1, 1]); // if value is less than 0, return an empty array, else if value is even, return an array with value, else return an array with value - 1 and 1
console.log(altered) // the output is [ 0, 1, 4, 1, 2, 4 ]

Adding arrays with concat()

concat() method

concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

1
2
3
// concat() method. nums is from the previous example.
console.log(nums.concat([12, 'Jaden',[10, "leaked",['Ahit',['bruv', 13]]]]).flat(Infinity));
console.log(nums)  // the output is [ 1, 5, 2, -4, 4, 12, 'Jaden', 10, 'leaked', 'Ahit', 'bruv', 13 ]

Subarrays with slice(), splice(), fill(), and copyWithin()

slice() method

slice() method is used to extract a section of an array and returns a new array.

1
2
3
//slice() method
let sliced = nums.slice(1, 3); // the first argument is the start index and the second argument is the end index (exclusive)
console.log(sliced); // the output is [ 5, 2 ]

splice() method

splice() method is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.

1
2
3
4
5
6
//splice() method
let spArr = [12, 45, "Jade", "Ryan", 2];
spArr.splice(0, 0, "Luke", ['Father', 'Forever']); // the first 0 is the index where the new elements should be added, the second 0 is the number of elements to be removed, the rest are the elements to be added
console.log(spArr); // [ 'Luke', [ 'Father', 'Forever' ], 12, 45, 'Jade', 'Ryan', 2 ]
spArr.splice(1, 1, ['Ryan', 'Son', "I love you!"], 'xoxo'); // the first 1 is the index where the new elements should be added, the second 1 is the number of elements to be removed, the rest are the elements to be added
console.log(spArr); // [ 'Luke', [ 'Ryan', 'Son', 'I love you!' ], 'xoxo', 12, 45, 'Jade', 'Ryan', 2 ] 

fill() method

fill() method is used to fill all the elements of an array from a start index to an end index with a static value. It returns the modified array.

1
2
3
4
//fill() method
let fillArr = [1, 2, 3, 4, 5];
fillArr.fill(0, 2, 4); // the first 0 is the value to fill the array with, the second 2 is the start index, the third 4 is the end index
console.log(fillArr); // the output is [ 1, 2, 0, 0, 5 ]

copyWithin() method

This method shallow copies part of an array to another location in the same array and returns it without modifying its length. The first argument is the index where the copied elements should be placed, the second argument is the index where the copying should begin, the third argument is the index where the copying should end (but not included).

1
2
3
4
5
6
7
8
9
10
11
12
13
let cpyArr = [1, 2, 3, 4, 5]
cpyArr.copyWithin(1)
console.log(cpyArr) // the output is [ 1, 1, 2, 3, 4 ]
cpyArr.copyWithin(2, 3, 5); // the output is [ 1, 1, 3, 4, 4 ]
console.log(cpyArr)
cpyArr.copyWithin(-2, -3, -1); // the output is [ 1, 1, 3, 3, 4 ]
console.log(cpyArr) // the output is [ 1, 1, 3, 3, 4 ]
cpyArr.copyWithin(-4, -5, -2);
console.log(cpyArr) // the output is [ 1, 1, 1, 3, 4 ]
cpyArr.copyWithin(2, 1)
console.log(cpyArr) // the output is [ 1, 1, 1, 1, 3 ]
cpyArr.copyWithin(0, -2, 5);
console.log(cpyArr) // the output is [ 1, 3, 1, 1, 3 ]

Array Searching and Sorting Methods

indexOf() and lastIndexOf() methods

  • indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
  • lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
1
2
3
4
5
6
7
8
//indexOf() and lastIndexOf()
let checker = [10, 2, 3, 43, 10, 10, NaN];
console.log(checker.indexOf(10)); // the output is 0
console.log(checker.lastIndexOf(10)); // the output is 5
console.log(checker.indexOf(NaN)); // the output is -1
console.log(checker.lastIndexOf(NaN)); // the output is 6
console.log(checker.indexOf(10, 1)); // the output is 4
console.log(checker.lastIndexOf(10, 4)); // the output is 4

includes() method

includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

1
2
3
4
5
6
//includes() method
let incArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(incArr.includes(5)); // the output is true
console.log(incArr.includes(10)); // the output is false
console.log(incArr.includes(5, 5)); // the output is false
console.log(incArr.includes(5, -5)); // the output is true

sort() method

sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

1
2
3
4
5
6
7
8
//sort() method
let sortArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(sortArr.sort()); // the output is [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
let sortArr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(sortArr2.sort()); // the output is [ 1, 10, 2, 3, 4, 5, 6, 7, 8, 9 ]
let sortArr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(sortArr3.sort((a, b) => a - b)); // the output is [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] -> ascending order
console.log(sortArr3.sort((a, b) => b - a)); // the output is [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] -> descending order

reverse() method

reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

1
2
3
//reverse() method
let revArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(revArr.reverse()); // the output is [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]

join() method

join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

1
2
3
4
5
6
7
//join() method
let joinArr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(joinArr.join()); // the output is 1,2,3,4,5,6,7,8,9
console.log(joinArr.join('')); // the output is 123456789
console.log(joinArr.join('-')); // the output is 1-2-3-4-5-6-7-8-9
console.log(joinArr.join(' ')); // the output is 1 2 3 4 5 6 7 8 9
console.log(joinArr.join(' + ')); // the output is 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9

Static Methods

Array.isArray() method

Array.isArray() method determines whether the passed value is an Array.

1
2
3
4
5
//Array.isArray() method
console.log(Array.isArray([1, 2, 3])); // the output is true
console.log(Array.isArray({foo: 123})); // the output is false
console.log(Array.isArray('foobar')); // the output is false
console.log(Array.isArray(undefined)); // the output is false

Array-like objects

Array-like objects are objects that have indexed properties and a length property like arrays.

The following code snippet shows how you can use the Array.from() method to convert an array-like object to an array.

1
2
3
4
5
//Array-like objects
function f() {
    return Array.from(arguments);
}
console.log(f(1, 2, 3)); // the output is [ 1, 2, 3 ]

The following code snippet shows how you can use the Array.from() method to convert a string to an array.

1
2
//Array-like objects
console.log(Array.from('foo')); // the output is [ 'f', 'o', 'o' ]

The following code shows how you can use Array methods on array-like objects.

1
2
3
//Working on array-like objects
let arrayLike = {0: "Luke", 1: "Ryan", 2: "We", length: 3};
console.log(Array.prototype.flatMap.call(arrayLike, value => value.length !== 4 ? [] : [value])); // the output is [ 'Luke', 'Ryan' ]

Strings as Arrays

1
2
3
4
5
6
//Strings as Arrays
let str = 'Hello World';
console.log(str[0]); // the output is H
console.log(str[1]); // the output is e
console.log(str[2]); // the output is l
console.log(str[-1]); // the output is undefined -> negative indexes are not allowed

We can also apply generic array methods (not just those specific to strings) on strings.

1
2
3
4
5
6
//Strings as Arrays
let str = 'Hello World';
console.log(str.length); // the output is 11
console.log(str.indexOf('o')); // the output is 4
console.log(str.lastIndexOf('o')); // the output is 7
Array.prototype.forEach.call(str, char => console.log(char)); // the output is H e l l o   W o r l d

Array Destructuring

This is a way of unpacking values from an array or properties from an object into distinct variables.

1
2
3
4
5
6
7
8
//Array Destructuring
let arr = [1, 2, 3, 4, 5];
let [a, b, c, d, e] = arr;
console.log(a); // the output is 1
console.log(b); // the output is 2
console.log(c); // the output is 3
console.log(d); // the output is 4
console.log(e); // the output is 5

Made with ❤️ by Francis K.

This post is licensed under CC BY 4.0 by the author.