Introduction to JavaScript arrays

A brief introduction to arrays, which are the key building blocks of JavaScript

An array is a collection of elements.

Array in JavaScript is notTypes ofthey themselves.

The array isObject.

We can initialize an empty array in two different ways:

const a = []
const a = Array()

The first is to useArray literal syntax. The second one uses the Array built-in function.

You can use the following syntax to pre-populate the array:

const a = [1, 2, 3]
const a = Array.of(1, 2, 3)

The array can contain any value, even different types of values:

const a = [1, 'Flavio', ['a', 'b']]

Since we can add arrays to arrays, we can create multidimensional arrays, which have very useful applications (such as matrices):

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

matrix[0][0] //1 matrix[2][0] //7

You can access any element of the array by referencing a zero-based index:

a[0] //1
a[1] //2
a[2] //3

You can initialize a new array with a set of values using the following syntax, which first initializes an array with 12 elements, and then fills each element as0digital:

Array(12).fill(0)

You can get the number of it by checking the number of elements in the arraylengthproperty:

const a = [1, 2, 3]
a.length //3

Note that you can set the length of the array. If the allocated number is greater than the current capacity of the array, nothing will happen. If you assign a smaller number, the array will be cut at that position:

const a = [1, 2, 3]
a //[ 1, 2, 3 ]
a.length = 2
a //[ 1, 2 ]

How to add items to the array

We can usepush()method:

a.push(4)

We can useunshift()method:

a.unshift(0)
a.unshift(-2, -1)

How to delete items from the array

We can usepop()method:

a.pop()

We can useshift()method:

a.shift()

How to join two or more arrays

You can concatenate multiple arrays usingconcat():

const a = [1, 2]
const b = [3, 4]
const c = a.concat(b) //[1,2,3,4]
a //[1,2]
b //[3,4]

You can also usespreadoperator(...) Like this:

const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]
c //[1,2,3,4]

How to find a specific item in an array

you can use itfind()Array method:

a.find((element, index, array) => {
  //return true or false
})

Returns the first item that returns true. If the element is not found, undefined is returned.

The commonly used syntax is:

a.find(x => x.id === my_id)

The above line will return the first element in the array with the following contentid === my_id.

findIndex()Similar tofind(), But returns the index of the first item that returns true, if not found, it returns-1:

a.findIndex((element, index, array) => {
  //return true or false
})

Another way isincludes():

a.includes(value)

If satisfied, return trueacontainvalue.

a.includes(value, i)

If satisfied, return trueacontainvalueAfter positioni.

Download mine for freeJavaScript beginner's manual


More js tutorials: