DEV Community

Cover image for Arrays in JS
Sakshi
Sakshi

Posted on

Arrays in JS

Arrays in JS

Declaration

const a = []
const a = Array()

pre-fill the array

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

An array can hold any value, even values of different types:

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

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

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

Declare and define arrays at same time

Array(12).fill(0)

Length of array

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

How to add an item to an array

At the end

a.push(3);

at the beginning of an array

a.unshift(5);

How to remove elements from the array

remove an item from the end of an array using the pop() method:

a.pop()

remove an item from the beginning of an array using the shift() method:

a.shift()

How to join two or more arrays

You can join multiple arrays by using concat():

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

spread operator (...) in this way:


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

How to find a specific item in the array

You can use the find() method of an array:

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

A commonly used syntax is:


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

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

Another method is includes():

a.includes(value)
Returns true if a contains value.
a.includes(value, i)
Returns true if a contains value after the position i.

Thanks for reading <3

Top comments (0)