array(JavaScript Variable data type)

06/07/2023

Japanese version.

Array is a data type used to store multiple values. An array has zero-indexed elements, meaning each element is stored with an index starting from 0.

Contents

Create

There are several ways to create an array in JavaScript. The following examples all have three elements, apple, banana and orange, in an array called fruits.

Using literal notation:

let fruits = ['apple', 'banana', 'orange'];

Using the Array constructor:

let fruits = new Array('apple', 'banana', 'orange');

Be careful when using the constructor with a single numeric argument, as it may be interpreted as the length of the array.

Using the Array.of() method:

let fruits = Array.of('apple', 'banana', 'orange');

It's similar to the Array constructor, but with the advantage that it doesn't interpret a single numeric argument as the length of the array.

Using the Array.from() method:

let fruits = Array.from(['apple', 'banana', 'orange']);

Used to create arrays from non-array iterable objects.

There are multiple ways to create an array in JavaScript, and the most common method is using the literal notation.

Empty (element 0) array

Using the literal notation:

let arr = [];

Using the Array constructor:

let arr = new Array();

Both methods will create an empty array with zero elements, but the literal notation method is more commonly used and considered to be simpler and more straightforward.

Get the number of elements.

const arr = ['apple', 'banana', 'orange', 'grape'];

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

In this example, we're using the length property to get the number of elements in the array. Since the array arr has 4 elements, the output will be 4.

Retrieve element.

To retrieve a value from a variable of type array, specify the index as follows

let arr = ['apple', 'banana', 'orange'];
let fruit = arr[1];

console.log(fruit); // 'banana'

In this example, we're retrieving the second element ('banana') from the arr array. arr[1] means "get the element at index 1 of the arr array".

Head

const arr = ['apple', 'banana', 'orange', 'grape'];
const firstElement = arr[0];

console.log(firstElement); // 'apple'

In this example, we're accessing the element at index 0 of the array arr to get the first element. The retrieved element is assigned to the variable firstElement and printed to the console.

Tail

const arr = ['apple', 'banana', 'orange', 'grape'];
const lastElement = arr[arr.length - 1];

console.log(lastElement); // 'grape'

In this example, we're accessing the element at index (length - 1) of the array arr to get the last element. The retrieved element is assigned to the variable lastElement and printed to the console.

All elements

For loop

const arr = ['apple', 'banana', 'orange', 'grape'];

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

In this example, we're getting the length of the arr array and using a for loop to access each element of the array. Within the for loop, we're using the variable i to access the index of the arr array, and each element is printed to the console.

for...of loop

const arr = ['apple', 'banana', 'orange', 'grape'];

for (const element of arr) {
  console.log(element);
}

In this example, we're using a for...of loop to access each element of the arr array. The variable element is assigned to each element in turn, and each element is printed to the console.

Two-dimensional array

A two-dimensional array in JavaScript is an array in which each element is itself an array, allowing data to be stored in a row and column format. Two-dimensional arrays are commonly used to represent structures such as tables or matrices.

Here's an example of creating and accessing a two-dimensional array:

// Create a 3x3 two-dimensional array
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Access specific elements
console.log(matrix[0][0]); // 1
console.log(matrix[1][2]); // 6
console.log(matrix[2][1]); // 8

In this example, a 3x3 two-dimensional array is created. Each element is an array, and you can access elements by specifying their row and column positions. The row and column indices start from 0. For example, matrix[0][0] represents the element 1 in the first row and first column.

You can also add elements or modify existing elements in a two-dimensional array:

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Modify a specific element
matrix[1][1] = 10;

// Add a new row
matrix.push([11, 12, 13]);

console.log(matrix);

In this example, the middle element of the two-dimensional array, matrix[1][1], is changed to 10. Additionally, a new row [11, 12, 13] is added to the array using matrix.push([11, 12, 13]).

Two-dimensional arrays are useful for representing multidimensional data and are commonly used in operations involving matrices, grid-based algorithms, and more.

Array methods

There are several useful methods for manipulating arrays. Here are some commonly used array methods:

push():Adds one or more elements to the end of an array.

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

Here's an example using the push() method:

let arr = ['apple', 'banana'];
arr.push('orange');

console.log(arr); // ['apple', 'banana', 'orange']

In this example, we're adding a new element 'orange' to the end of the arr array using the push() method. The push() method modifies the original array arr and returns the new array ['apple', 'banana', 'orange'].

The push() method also allows you to add multiple elements at once.

let arr = ['apple', 'banana'];
arr.push('orange', 'grape');

console.log(arr); // ['apple', 'banana', 'orange', 'grape']

In this example, we're using the push() method to add two new elements 'orange' and 'grape' to the end of the arr array.

The push() method is frequently used to add elements to the end of an array.

pop():emoves an element from the end of an array and returns that element.

The JavaScript array method pop() removes an element from the end of an array and returns that element.

Here's an example of using the pop() method to remove an element from an array:

const arr = ['apple', 'banana', 'orange', 'grape'];
const removedElement = arr.pop();

console.log(arr); // ['apple', 'banana', 'orange']
console.log(removedElement); // 'grape'

In this example, we're using the pop() method to remove an element from the end of the arr array. The removed element is assigned to the variable removedElement and printed to the console. The pop() method modifies the original array by removing an element from the end.

If the array is empty, the pop() method returns undefined.

The pop() method is a convenient way to remove an element from the end of an array. However, if you want to remove an element from the beginning of an array, you need to use the shift() method.

unshift():Adds one or more elements to the beginning of an array and returns the new length of the array.

const arr = ['orange', 'grape'];
const newLength = arr.unshift('apple', 'banana');

console.log(arr); // ['apple', 'banana', 'orange', 'grape']
console.log(newLength); // 4

In this example, we're using the unshift() method to add the elements 'apple' and 'banana' to the beginning of the arr array. The added elements change the order of the array, and the new length of the updated array is 4.

shift():removes one element from the beginning of an array and returns the removed element.

const arr = ['apple', 'banana', 'orange', 'grape'];
const shiftedElement = arr.shift();

console.log(shiftedElement); // 'apple'
console.log(arr); // ['banana', 'orange', 'grape']

In this example, we're using the shift() method to remove the element 'apple' from the beginning of the arr array. The removed element is assigned to the variable shiftedElement and printed to the console. The array after the removal is ['banana', 'orange', 'grape'], which is the same as the original array with the first element removed.

Unlike the unshift() method, the shift() method returns the removed element rather than the new length of the updated array. Additionally, the shift() method is useful for processing an array in order from the beginning, as it removes one element at a time from the beginning of the array.

slice():Retrieves a portion of an array, including the elements between the specified start and end positions.

const arr = ['apple', 'banana', 'orange', 'grape'];
const slicedArr = arr.slice(1, 3);

console.log(slicedArr); // ['banana', 'orange']
console.log(arr); // ['apple', 'banana', 'orange', 'grape']

In this example, we're using the slice() method to retrieve an array containing the elements between index 1 and index 3 (exclusive) of the arr array. The returned array is ['banana', 'orange'], and the original arr array is unchanged and remains ['apple', 'banana', 'orange', 'grape'].

The slice() method can retrieve a portion of an array by specifying start and end positions. If the start position is omitted, retrieval begins from the beginning of the array. If the end position is omitted, retrieval continues to the end of the array. Negative indices can also be specified, in which case the position is relative to the end of the array.

The slice() method is useful for retrieving a portion of an array without modifying the original array, allowing you to obtain the desired elements as a new array.

splice():Removes or replaces elements in an array or adds new elements.

const arr = ['apple', 'banana', 'orange', 'grape'];
const removedElements = arr.splice(1, 2);

console.log(removedElements); // ['banana', 'orange']
console.log(arr); // ['apple', 'grape']

In this example, we're using the splice() method to remove two elements starting at index 1 of the arr array. The removed elements are assigned to the variable removedElements and printed to the console. The original arr array is modified to be ['apple', 'grape'], with the removed elements ['banana', 'orange'] deleted.

The splice() method is useful for removing elements from an array or adding new elements to it. It can also be used to replace elements in an array. Note that unlike the slice() method, splice() modifies the original array when removing elements.

The splice() method removes elements from an array by specifying the starting index and the number of elements to remove. The removed elements are returned as a new array. To add elements, you need to specify the insertion position and the new elements.

concat():Combines two or more arrays and creates a new array.

const arr1 = ['apple', 'banana'];
const arr2 = ['orange', 'grape'];
const concatenatedArr = arr1.concat(arr2);

console.log(concatenatedArr); // ['apple', 'banana', 'orange', 'grape']
console.log(arr1); // ['apple', 'banana']
console.log(arr2); // ['orange', 'grape']

In this example, we're using the concat() method to combine arr1 and arr2 into a new array called concatenatedArr. The resulting array contains all the elements of arr1 followed by all the elements of arr2, and the original arr1 and arr2 arrays remain unchanged.

The concat() method can combine two or more arrays, which are passed as arguments, and returns a new array containing all the concatenated elements. The original arrays are not modified.

The concat() method is useful for combining arrays. You can combine different arrays to create a new array. You can also combine multiple arrays in sequence.

Note that concat() method can also accept non-array values as arguments, in which case the value is added as a single element to the end of the new array.

indexOf():returns the index of the first occurrence of a specified element in an array.

const arr = ['apple', 'banana', 'orange', 'grape'];
const index1 = arr.indexOf('orange');
const index2 = arr.indexOf('kiwi');

console.log(index1); // 2
console.log(index2); // -1

In this example, we're using the indexOf() method to search for the index of the elements 'orange' and 'kiwi' in the arr array. The element 'orange' is found at index 2, and 'kiwi' is not found in the array, so -1 is returned.

The indexOf() method is useful for searching for the index of elements in an array. You can use it to check if an element exists in the array. You can also use it to search for the first index of duplicate elements in an array.

The indexOf() method searches for the index of an element in an array starting from the beginning of the array. If you want to start the search from the end of the array, you can use the lastIndexOf() method.

lastIndexOf():Returns the index of the last occurrence of a specified element in an array.

const arr = ['apple', 'banana', 'orange', 'banana', 'grape'];
const index1 = arr.lastIndexOf('banana');
const index2 = arr.lastIndexOf('kiwi');

console.log(index1); // 3
console.log(index2); // -1

In this example, we're using the lastIndexOf() method to search for the last index of the elements 'banana' and 'kiwi' in the arr array. The element 'banana' is found at the last index 3, and 'kiwi' is not found in the array, so -1 is returned.

The lastIndexOf() method is useful for searching for the last index of elements in an array. You can use it to check if an element exists in the array. You can also use it to search for the last index of duplicate elements in an array.

The lastIndexOf() method searches for the index of an element in an array starting from the end of the array. If you want to start the search from the beginning of the array, you can use the indexOf() method.

join():Converts all the elements in an array into a string and concatenates them into one string with a specified separator.

const arr = ['apple', 'banana', 'orange'];
const joinedArr = arr.join(', ');

console.log(joinedArr); // 'apple, banana, orange'

In this example, we're using the join() method to concatenate the elements in the arr array into a string separated by a comma and a space.

The join() method is useful for concatenating the elements in an array. You can use the concatenated string to display the contents of the array.

Since the join() method converts the elements in an array to a string, each element in the array is automatically converted to a string. If the elements in the array are objects or numbers, they are automatically converted to strings.

If you don't pass an argument to the join() method, the default separator is a comma.

reverse():Reverses the order of the elements in an array.

const arr = ['apple', 'banana', 'orange'];
arr.reverse();

console.log(arr); // ['orange', 'banana', 'apple']

In this example, we're using the reverse() method to reverse the order of the elements in the arr array.

The reverse() method is useful for reversing the order of elements in an array. Note that this method modifies the original array, so be careful when using it.

sort():Sorts the elements in an array.

const arr = [5, 1, 4, 2, 8];
arr.sort((a, b) => a - b);

console.log(arr); // [1, 2, 4, 5, 8]

In this example, we're using the sort() method to sort the numeric elements in the arr array in ascending order. In this case, we're passing a comparison function to the sort() method. The comparison function takes two arguments, which are two elements to be compared, and should return a negative integer, zero, or a positive integer. If the function returns a negative integer, the first argument is considered smaller than the second argument. If the function returns zero, the two elements are considered equal. If the function returns a positive integer, the first argument is considered greater than the second argument.

The sort() method is useful for sorting the elements in an array. By using a comparison function, you can sort the elements according to custom rules. For example, you can sort an array of numbers in descending order, or sort an array of objects by a specific property.

filter():Creates a new array with all elements that pass the test implemented by the provided function.

const arr = [1, 2, 3, 4, 5, 6];
const evenNumbers = arr.filter(num => num % 2 === 0);

console.log(evenNumbers); // [2, 4, 6]

In this example, we're using the filter() method to extract only the even numbers from the arr array. The filter() method takes a function as an argument that tests whether each element in the array passes a certain condition. The function is executed for each element in the array, and only the elements that pass the condition are included in the new array.

The filter() method is useful for extracting elements from an array that meet a certain condition. By using this method, you can easily get only the elements that match a specific criterion.

The elements that are extracted by the filter() method are of the same type as the elements in the original array and their order is preserved. The filter() method creates a new array, so the original array is not modified.

map():Creates a new array with the results of calling a provided function on every element in the calling array.

const arr = [1, 2, 3, 4, 5];
const doubled = arr.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]

In this example, we're using the map() method to double every element in the arr array. The map() method takes a function as an argument that executes on each element in the array, and the new value is stored in the new array.

The map() method is useful for transforming the elements in an array. By using this method, you can easily transform each element in an array. Also, since the method creates a new array with the same number of elements as the original array, you can create a new array with the same number of elements as the original array.

The elements that are transformed by the map() method are stored as elements in the new array. The original array is not modified, and a new array is created.

reduce():Executes a provided function for each element in the array and returns a single value.

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, num) => total + num, 0);

console.log(sum); // 15

In this example, we're using the reduce() method to calculate the sum of the elements in the arr array. The reduce() method takes a function as an argument and an initial value. The function is executed for each element in the array, and the result is passed to the next call along with the next element. The initial value is passed as the first argument to the function on the first call.

The reduce() method is useful for reducing the elements in an array to a single value. By using this method, you can easily calculate the sum or average of an array.

The value returned by the reduce() method is the return value of the last executed function.

forEach():Executes a provided function for each element in the array.

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

arr.forEach(num => console.log(num));

In this example, we're using the forEach() method to log each element in the arr array to the console. The forEach() method takes a function as an argument and executes it for each element in the array.

The forEach() method is useful for iterating over the elements in an array. By using this method, you can easily process each element in an array. Additionally, you can modify the elements in the array.

The forEach() method does not return a value. The function passed as an argument is simply executed for each element in the array.

every():Checks whether all elements in an array meet a specified condition.

const arr = [2, 4, 6, 8, 10];
const allEven = arr.every(num => num % 2 === 0);

console.log(allEven); // true

In this example, we're using the every() method to check whether all elements in the arr array are even. The every() method takes a function as an argument and executes it for each element in the array. If the function returns false, the every() method stops processing and returns false. If all elements return true from the function, the every() method returns true.

The every() method is useful for checking whether all elements in an array meet a specific condition. By using this method, you can easily check whether all elements in an array meet a condition.

Note that if the array is empty, the every() method always returns true.

some():Checks whether any element in an array meets a specified condition.

const arr = [2, 4, 6, 8, 10];
const someOverTen = arr.some(num => num >= 10);

console.log(someOverTen); // true

In this example, we're using the some() method to check whether any element in the arr array is greater than or equal to 10. The some() method takes a function as an argument and executes it for each element in the array. If the function returns true, the some() method stops processing and returns true. If all elements return false from the function, the some() method returns false.

The some() method is useful for checking whether any element in an array meets a specific condition. By using this method, you can easily check whether any element in an array meets a condition.

Note that if the array is empty, the some() method always returns false.

find():Returns the first element in an array that satisfies a specified condition.

const arr = [1, 3, 4, 5, 7, 8];
const firstEven = arr.find(num => num % 2 === 0);

console.log(firstEven); // 4

In this example, we're using the find() method to search for the first even number in the arr array. The find() method takes a function as an argument and executes it for each element in the array. If the function returns true, the find() method returns that element and stops processing. If all elements return false from the function, the find() method returns undefined.

findIndex():Returns the index of the first element in an array that satisfies a specified condition.

const arr = [1, 3, 4, 5, 7, 8];
const firstEvenIndex = arr.findIndex(num => num % 2 === 0);

console.log(firstEvenIndex); // 2

In this example, we're using the findIndex() method to search for the first even number in the arr array and return its index. The findIndex() method takes a function as an argument and executes it for each element in the array. If the function returns true, the findIndex() method returns the index of that element and stops processing. If all elements return false from the function, the findIndex() method returns -1.

---

Links

JavaScript Articles