Arrays in JavaScript

Arrays in JavaScript

In-depth knowledge on array methods

Hola coders!

In this article, we will learn about arrays in JavaScript. We will cover all the properties and methods used with arrays in JavaScript.

Before, jumping into methods and properties, let's first get an idea about what an array is.

What is an Array🤔?

Array is an inbuilt data structure in JS which allows you to store multiple values under a single variable name. Arrays consist of the homogeneous datatype(value) i.e., either all the elements can be of string, number, or any other datatype. Square brackets[ ] are used to declare/represent an Array.

Syntax to create an array

const arr_name = [val1, val2, val3, ..... ]

// not recommended method
const arr_name = new Array(val1, val2, val3, .....)

Example

// declaring an array 
const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerala", "Assam"]
console.log(states)


const marks = new Array(1, 2, 3, 4, 5, 6)
console.log(marks)

Characteristics of JS Array

  • Arrays in JavaScript can contain heterogeneous values (different datatypes) but an array with homogeneous values (same datatype) is recommended and used.

  • Any element in JavaScript array can be accessed using the index number (which is a positive integer value referring to the position of an element in the array).

  • JavaScript arrays are zero-indexed, meaning the first element is at index (position) 0.

  • JavaScript arrays are flexible, they can be resized.

Array Property

  • length

JavaScript Arrays consist of length property which determines the length of the array

Syntax

array_name.length

Example

// declaring an array 
const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerela", "Assam"]
// no of elements in the array
console.log(states.length) \\ 5

Array Methods

  • at( )

Syntax

array_name.at(index_num)

at( ) method returns the element at the given index.It accepts negative integers which count the element from the end starting from -1.

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
console.log(`Fruit at index 1 is: ${fruits.at(1)}`) // apple
console.log(`Fruit at index -2 is: ${fruits.at(-2)}`) // grapes
  • concat( )

Syntax

array1.concat(array2)

concat( ) method returns a new array that joins the two arrays.

const fruits1 = ["mango", "apple", "banana", "grapes", "guava"]
const fruits2 = ["pineapple", "plum", "pear"]
const fruits3 = fruits1.concat(fruits2)
console.log(fruits3)

1.PNG

  • copyWithin()

copyWithin() method copies the sequence of elements from one place to another within the array, without changing the length of the array.

Syntax

array_name.copyWithin(target, start_index)

// end_index not included
array_name.copyWithin(target, start_index, end_index)

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava", "pineapple", "plum", "pear"]
//copies all elements from index 6 till last at index 1
fruits.copyWithin(1,6)
console.log(fruits)

2.PNG

const fruits = ["mango", "apple", "banana", "grapes", "guava", "pineapple", "plum", "pear"]
//copies all elements from index 3 till 5 at index 0
fruits.copyWithin(0, 3, 6)
console.log(fruits)

3.PNG

  • entries( )

Syntax

iterator = array_name.enteries()

entries( ) method returns an Array iterator object that contains key-value pair for each element in the array. Index no is the key where the element is the value.

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const iterator = fruits.entries()

console.log(iterator)

// returns key value pair for element at index 0
console.log(iterator.next().value)
// returns key value pair for element at next index 1
console.log(iterator.next().value)

Output

4.PNG

  • every( )

Syntax

array_name.every(function_ref)

every( ) method returns true/false boolean value. It returns true if, all the elements in the array pass the test implemented by the function passed as an argument.

Example

function checkOdd (num){
    return num % 2 != 0
}

const nums = [1, 5, 7, 9]
console.log(nums.every(checkOdd))   // true

const num2 = [2, 1, 3, 11]
console.log(nums.every(checkOdd))   // false
  • some( )

Syntax

array_name.some(function_ref)

every( ) method returns true/false boolean value. It returns true if, atleast one element in the array passes the test implemented by the function passed as an argument.

Example

function checkOdd (num){
    return num % 2 != 0
}

const nums = [1, 2, 4, 8]

console.log(nums.some(checkOdd))  //true
  • fill( )

Syntax

array_name.every(value)
array_name.every(value, start_index, end_index)

fill( ) method fills the array with a certain value passed during the function call.

Example

const arr = [1, 2, 3, 4, 5, 6]
// will fill all elements with 0
console.log(arr.fill(0))

// will elements from index 3 to 4 with value 0 
const arr2 = [2, 4, 6, 8, 10, 12]
console.log(arr2.fill(0,3,5))

Output

5.PNG

  • filter( )

Syntax

array_name.filter(function_ref)

filter( ) method as the name suggests, filters out the elements from the array that pass the condition provided in the function.

Example

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

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const ans = fruits.filter( fruit => fruit.length > 5)
console.log(ans)

Output

6.PNG

  • find( )

Syntax

array_name.find(function_ref)

find( ) method returns the first element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, undefined is returned

Example

const arr = [1, 11, 3, 4, 5, 6]
const res = arr.find( num => num % 2 == 0)
console.log(res)  // 4

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const ans = fruits.find( fruit => fruit.length > 6)
console.log(ans)  // undefined
  • findIndex( )

Syntax

array_name.findIndex(function_ref)

findIndex( ) method returns the index of the first element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, -1 is returned

Example

const arr = [1, 11, 3, 4, 5, 6]
const res = arr.findIndex( num => num % 2 == 0)
console.log("Index is: " ,res)    // Index is: 3

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const ans = fruits.findIndex( fruit => fruit.length > 6)
console.log("index is: " , ans)    // index is: -1
  • findLast( )

Syntax

array_name.findLast(function_ref)

findLast( ) method returns the last element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, undefined is returned

Example

const arr = [1, 11, 3, 4, 5, 6]
const res = arr.findLast( num => num % 2 == 0)
console.log(res)  // 6

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const ans = fruits.findLast( fruit => fruit.length > 6)
console.log(ans)  // undefined

This function will execute in the browser console.

  • findLastIndex( )

Syntax

array_name.findLastIndex(function_ref)

findLastIndex( ) method returns the index of the last element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, -1 is returned

Example

const arr = [1, 11, 3, 4, 5, 6]
const res = arr.findLastIndex( num => num % 2 == 0)
console.log("Index is: " ,res)    // Index is: 5

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
const ans = fruits.findLastIndex( fruit => fruit.length > 6)
console.log("index is: " , ans)    // index is: -1
  • flat( )

Syntax

array_name.flat()
array_name.flat(depth)

flat( ) method returns flatten array. In case, the array is multi-dimensional or any element within the array is multi-dimensional then it flattens it and if we pass on the depth as an argument, it flattens till the depth level is provided.

const arr = [[1,2,3], [4,5,6]]
const flat_arr = arr.flat()
console.log(flat_arr)

const my_arr = [1, 2, 3, [[4, 5, 6]]]
const flat_arr1 = my_arr.flat(1)
console.log(flat_arr1)

const flat_my_arr = my_arr.flat(2)
console.log(flat_my_arr)

Output

7.PNG

  • map( )

Syntax

array_name.map(callback_function)

map( ) method populates a new array, with the values computed by the callback function on every element. It also allows traversing array elements without using loops.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava", "pineapple", "plum", "pear"]
fruits.map( fruit => console.log(fruit))

Output

15.PNG

const fruits = ["mango", "apple", "banana", "grapes", "guava", "pineapple", "plum", "pear"]
//all fruits name changed to uppercase
const fruits_upper = fruits.map( fruit => fruit.toUpperCase())
console.log(fruits_upper)

Output

16.PNG

  • flatMap( )

Syntax

array_name.flatMap(callback_function)

flatMap( ) method is a combination of map and flat method. It returns a new array by applying callback computation on each element and flattening the array by level 1. Instead of using both methods separately, this could be used.

Example

const my_arr = [1, 2, 3, [[4, 5, 6]]]

console.log(my_arr.flatMap(num => num))

// [ 1, 2, 3, [ 4, 5, 6 ] ]
  • forEach( )

Syntax

array_name.forEach()

forEach( ) method travels through each element in the array and it executed the callback function once for each element.

arr_name.forEach(callback_function)

Example

const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerela", "Assam"]
states.forEach( (val, idx , arr) => {
    return console.log(`${idx} -- ${val}  -- ${arr}`)
})

8.PNG

const nums = [1, 5, 7, 9]
nums.forEach( (val, idx, arr) => {
    arr[idx] += 1
})

console.log(nums)
// [2, 6, 8, 10]
  • from( )

Syntax

Array.from(iterable)

Array.from( ) method creates a new static array from an iterable object.

Example

const arr = Array.from("John Doe")
console.log(arr)

9.PNG

  • includes( )

Syntax

array_name.includes(value)

includes( ) method returns a true value if the value is present in the given array and returns false if the value is not present.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
console.log(`IS pineapple present in the array: ${fruits.includes("pineapple")}`)

const arr = [1, 11, 3, 4, 5, 6]
console.log(`Is 11 present is the array : ${arr.includes(11)}`)

Output

10.PNG

  • indexOf( )

Syntax

array_name.indexOf(value)

indexOf( ) method returns the first index position at which value is present in the given array or, returns -1 if value is not present.

Example

const arr = [1, 2, 3, 11, 4, 5, 6, 11]
console.log(`Index at which value 11 is present in the array : ${arr.indexOf(11)}`)

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
console.log(`Index at which value pineapple is present in the array : ${fruits.indexOf("pineapple")}`)

Output

11.PNG

  • lastIndexOf( )

Syntax

array_name.lastIndexOf(value)

lastIndexOf( ) method returns the last index position at which value is present in the given array or, returns -1 if value is not present.

Example

const arr = [1, 2, 3, 11, 4, 5, 6, 11]
console.log(`Last Index at which value 11 is present in the array : ${arr.lastIndexOf(11)}`)

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
console.log(`Last Index at which value pineapple is present in the array : ${fruits.lastIndexOf("pineapple")}`)

Output

14.PNG

  • Array.isArray()( )

Syntax

Array.isArray(value)

Array.isArray() method checks whether the given value is an array or not. It returns true if value is an array else false.

Example

const arr = [1, 2, 3, 11, 4, 5, 6, 11]
console.log(`Is it an array: ${Array.isArray(arr)}`)

let fullName = "John Doe"
console.log(`Is it an array: ${Array.isArray(fullName)}`)

Output

12.PNG

  • join( )

Syntax

array_name.join()
array_name.join(separator)

join( ) method joins all the adjacent values of the array with the separator and returns a string. If a separator is not provided then comma(,) is used as a separator by default.

Example

const arr = [1, 2, 3, 11, 4, 5, 6, 11]
console.log(`joining arr values: ${arr.join()}`)

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
console.log(`concatenating using '-': ${fruits.join('-')}`)

Output

13.PNG

toString()

Syntax

array_name.toString()

array_name.toLocaleString( ) method returns values of an array as a comma separated string.

Example

const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerela", "Assam"]
console.log(states.toString())
// Output: Haryana,Punjab,Tamil Nadu,Kerela,Assam
  • keys( )

Syntax

array_name.keys()

keys( ) method returns an Array iterator object that iterates the index value.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
iterator = fruits.keys()

// returns key as index 0
console.log(iterator.next().value)      // 0

// returns key vas index 1
console.log(iterator.next().value)     // 1
  • values( )

Syntax

array_name.values()

values( ) method returns an Array iterator object that iterates the array value.

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
iterator = fruits.values()

// returns value at index 0
console.log(iterator.next().value)      // mango

// returns value at index 1
console.log(iterator.next().value)     // apple
  • Array.of( )

Syntax

Array.of(element0, element1, .....)

Array.of( ) method creates an array according to the value and number of arguments passed despite the type of arguments.

It is different from Array constructor as array constructor creates an empty array of length passed as an argument whereas Array.of() method creates an array with the values passed in it as an argument.

Example

//creates an array with only element 7
const arr = Array.of(7)
console.log(arr)
console.log(`Length of arr is : ${arr.length}`)

// creating an array of the length of value 5
const new_arr = new Array(7)
console.log(new_arr)
console.log(`Length of arr is : ${new_arr.length}`)

Output

17.PNG

  • pop( )

Syntax

array_name.pop()

array_name.pop( ) method removes the last element from the array and returns that element. It changes the length of the array.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
let popped_element = fruits.pop()
console.log(`last element popped out is: ${popped_element}`)
console.log(fruits)
console.log(fruits.length)

Output

18.PNG

  • push( )

Syntax

array_name.push(element0, element1, ...)

array_name.push( ) method adds one or more elements at the last of the array. It changes the length of the array and returns the new length of the array.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
let new_len = fruits.push("pear")
console.log(`new length of the array: ${new_len}`)
console.log(fruits)

Output

19.PNG

  • reduce( )

Syntax

array_name.reduce(callback_function, initial_value)
array_name.reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)

array_name.reduce( ) method computes the callback function on each element to reduce the array elements and populate a single value. It is an accumulator function that accumulates all the array values into a single value.

The initial value is the first parameter(previousValue) of the call, if it is not provided then the element at index 0 (first array element) is used as the initial value and iteration starts from the element at index 0 (second element in the array).

Example

const arr = [1, 2, 3, 4, 5, 6]
let reduced_val = arr.reduce( ( prevVal, currentVal ) => prevVal + currentVal)
console.log(reduced_val)     // 21
let reduced_val2 = arr.reduce( (( prevVal, currentVal ) => prevVal + currentVal) , 10)
console.log(reduced_val2)    //31
  • reduceRight( )

Syntax

array_name.reduceRight(callback_function, initial_value)
array_name.reduceRight((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)

array_name.reduceRight( ) method computes the callback function on each element to reduce the array elements and populate a single value. It computes the array values from right to left unlike reduce method.

The initial value is the first parameter(previousValue) of the callback function, if it is not provided then the element at index 0 (first array element) is used as the initial value and iteration starts from the element at index 0 (second element in the array).

Example

const arr = [1, 2, 3, 4, 5, 6]
let reduced_val = arr.reduceRight( ( prevVal, currentVal ) => prevVal + currentVal)
console.log(reduced_val)    21
let reduced_val2 = arr.reduceRight( (( prevVal, currentVal ) => prevVal + currentVal) , 10)
console.log(reduced_val2)   //31

const arr2 = [[1, 2], [3, 4], [5, 6]]
let new_val3 = arr2.reduceRight( (prevVal, currentVal) => prevVal.concat(currentVal) )
console.log(new_val3)   // [ 5, 6, 3, 4, 1, 2 ]

Difference between reduce and reduceRight

const a = ["1", "2", "3", "4", "5"];
const left = a.reduce((prev, cur) => prev + cur);
const right = a.reduceRight((prev, cur) => prev + cur);

console.log(left); // "12345"
console.log(right); // "54321"
  • reverse( )

Syntax

array_name.reverse()
array_name.reverse()

array_name.reverse( ) method reverses the order of position of values in the array and returns the reversed array

Example

const a = ["1", "2", "3", "4", "5"];
console.log(a.reverse())    //[ '5', '4', '3', '2', '1' ]
  • shift( )

Syntax

array_name.shift()

array_name.shift( ) method removes the element from start(index 0) of an array. It changes the length of the array.

Example

const a = ["1", "2", "3", "4", "5"];
console.log(`array length before applying shift function: ${a.length}`)
console.log(a.shift())
console.log(`array length after applying shift function: ${a.length}`)

output

20.PNG

  • unshift( )

Syntax

array_name.unshift(element0, element1, ...)

array_name.unshift( ) method adds one or multiple elements at the start (index 0) of an array. It returns the new length of the array.

Example

const a = ["1", "2", "3", "4", "5"];
console.log(`array length before applying shift function: ${a.length}`)
a.unshift("99", "88")
console.log(a)
console.log(`array length after applying shift function: ${a.length}`)

Output

21.PNG

  • slice( )

Syntax

array_name.slice()
array_name.slice(start_index)
array_name.slice(start_index, end_index)

array_name.slice( ) method returns a copy of a part of an array. It does not modify the original array. Negative indexes can also be provided which slice out from right to left. start_index is included but end_index is not included.

Example

const fruits = ["mango", "apple", "banana", "grapes", "guava", "pineapple", "plum", "pear"]
// it returns entire array
console.log(fruits.slice())
console.log("##############")

// slices out till end starting from index 3
console.log(fruits.slice(3))
console.log("##############")

// starts from -2 index till end
// from right to left indexing starts from -1
console.log(fruits.slice(-2))
console.log("##############")

// slices out array starting from index 3 till index 6
console.log(fruits.slice(3,7))
console.log("##############")

Output

22.PNG

sort()

Syntax

array_name.sort()
array_name.slice(comparison_function)

array_name.sort( ) method sorts the given array and provides the reference of the array. It sorts the actual positions in the array. Compare function reference can also be passed to customize the sorting functionality. By default, it sorts in ascending order.

Example

const nums = [1, 2, 4, 3, 8, 5]
nums.sort()
console.log(nums)  // [ 1, 2, 3, 4, 5, 8 ]

const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerela", "Assam"]
states.sort()
console.log(states)
// [ 'Assam', 'Haryana', 'Kerela', 'Punjab', 'Tamil Nadu' ]

const numbers = [1, 2, 4, 3, 8, 5]
numbers.sort(function (a, b) {
    return b - a;
  });

console.log(numbers)
// [ 8, 5, 4, 3, 2, 1 ]

splice()

Syntax

array_name.splice(index, delete_count, item1, item2, ....)

array_name.splice( ) method adds multiple elements at a given index, and even deletes

Example

const states = ["Haryana", "Punjab", "Tamil Nadu", "Kerela", "Assam"]
// no value is deleted, Nagaland and MAharashtra added from index 2
states.splice(2, 0, 'Nagaland', 'Maharashtra')

console.log(states)

Output

23.PNG

const fruits = ["mango", "apple", "banana", "grapes", "guava"]
// from index 1 two values are deleted and pineapple is added
fruits.splice(1, 2, 'pineapple')
console.log(fruits)

Output

24.PNG

toLocaleString()()

Syntax

array_name.toLocaleString(locale, option)

array_name.toLocaleString( ) method returns values of an array in string format. Array is converted into a string using toLocaleString method. It simply returns the date object into a string using locale settings of the system.

Example

const now = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// British English uses day-month-year order and 24-hour time without AM/PM
console.log(now.toLocaleString('en-GB', { timeZone: 'UTC' }));
// expected output: 20/12/2012, 03:00:00

// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(now.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// expected output: 2012. 12. 20. 오전 3:00:00

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!