JavaScript : Array

JavaScript : Array

A widely used data structure in programming world.

What is an Array?

Collection of values arranged in a sequence. Usually, we use an array data structure, when we need to store multiple values one after another.

//Example 1 - Store numbers from 1 to 5.
let arr = [1, 2, 3, 4, 5] 

//Example 2 - Store values of multiple data types.
let arr = [1, "Subham", 3, "Sahu", 5]

Declaring an array.

Two ways by which we can create an array. Remember, both ways create the same array, internally they are treated as objects only. Yes, Array is an object in JavaScript.

//Option 1: Use array literal.
let arr = ['a', 'b', 'c', 'd', 'e']

//Option 2: Use Array constructor. 
let arr = new Array('a', 'b', 'c', 'd', 'e')

Access array values and Indexing

To define the position of values in an array, we assign each value with an index starting from 0 to array_length - 1. To access values in the array, we use these indexes to refer to a unique value in the array.

Group 1.png

To access the nth value in the array - array_name[n - 1] or array_name.at(n-1)

//Example : Access 5th value in arr.
let arr = ['a', 'b', 'c', 'd', 'e']
console.log(arr[4]) // output: e 
console.log(arr.at(4)) // output: e

Let's explore more about the array.

As we know, the array is an object, so let's dive into its properties and methods.

1) length

Returns the length of the array. A total number of values in the array. let arr = [1, "a", 2, "b", 3, "c", 4, "d"] console.log(arr.length) // output: 8

2) at() & indexOf()

  • at(index) returns the value at index in arr.

  • indexOf(value) returns the index of the value in arr.

let arr = [1, "a", 2, "b", 3, "c", 4, "d"]
console.log(arr.at(1)) // output: a
console.log(arr.indexOf("b") // output: 3

3) push() & pop()

  • push(...values) append values to the end of arr and returns the length of modified arr.

  • pop() deletes a value from the end of arr and returns the deleted value.

let arr = [1, "a", 2, "b", 3, "c", 4, "d"] 
console.log(arr.push(5, "e")) // 10
console.log(arr) //  [1, "a", 2, "b", 3, "c", 4, "d", 5, "e"]

console.log(arr.pop()) // e
console.log(arr.pop()) // 5
console.log(arr) // [1, "a", 2, "b", 3, "c", 4, "d"]

4) shift() & unshift()

  • shift() deletes a value from the front of arr and returns the deleted value.

  • unshift(...values) append values to the front of arr, and returns the length of modified arr.

let arr = [1, "a", 2, "b", 3, "c", 4, "d"] 
console.log(arr.shift()) // 1
console.log(arr.shift()) // a
console.log(arr) //  [2, "b", 3, "c", 4, "d"]

console.log(arr.unshift(1, "a")) // 8
console.log(arr) // [1, "a", 2, "b", 3, "c", 4, "d"]

Before moving further, be noted that not every array method modifies the array. Array methods can be classified into two categories

  1. Methods that modify the array, but do not return a new array. eg. push, pop, shift, unshift etc.

  2. Methods that do not modify the original array, but return the new array. eg. reverse, slice, map, filter etc.

5) slice(start, end)

Returns a new array, containing values starting from start index to (end - 1) index.
javascript let arr = [1, "a", 2, "b", 3, "c", 4, "d"] console.log(arr.slice(0,7)) // logs values from index 0 to 6 [1, "a", 2, "b", 3, "c", 4] console.log(arr.slice(1,7)) // logs values from index 1 to 6 ["a", 2, "b", 3, "c", 4]

6) splice(start, delete_count, replace values)

Replaces arr values starting from start index upto delete count and returns a new array containing deleted elements.

let arr = [1, "a", 2, "b", 3, "c", 4, "d"] 
console.log(arr.splice(0, 2, "0", "null")); // [1, "a"]
console.log(arr); // [0 ,"null",  2, "b", 3, "c", 4, "d"]

7) reverse()

Reverses all values of an array in place, and returns a reference to the array. javascript let arr = [1, "a", 2, "b", 3, "c", 4, "d"] console.log(arr.reverse()); // ["d", 4, "c", 3, "b", 2, "a", 1] console.log(arr); // ["d", 4, "c", 3, "b", 2, "a", 1]

8) sort()

Sorts all values of an array in place, and returns a reference to the array. javascript let arr = [1, "a", 2, "b", 3, "c", 4, "d"] console.log(arr.sort()); // [1, 2, 3, 4, "a", "b", "c", "d"] console.log(arr); // [1, 2, 3, 4, "a", "b", "c", "d"]

9) forEach(callback)

Calls a given function on every item of arr. ```javascript //Example: Log type of each item in arr.

let arr = [1, "a", 2, "b", 3, "c", 4, "d"] arr.forEach(item => console.log(typeof(item)); // ['number', 'string', 'number', 'string', 'number', 'string', ] ```

10) map(callback)

Returns new array, containing values returned by callback function on each item.

/* Example: Return new array, with following operations on each item. 
      - If item is number, do item - 1
      - else , do item.toUppercase() 
*/

let arr = [1, 2, 3, 4, "a", "b", "c", "d"] 

let newArr = arr.map(item => {
      if(typeof(item) === 'number'){
            return item - 1 
      }else{
            return item.toUpperCase();
      }
});

console.log(newArr) // Logs [0, 1, 2, 3, "A", "B", "C", "D"]

11) filter(callback)

Returns a new array, containing items on which callback returns true.

//Example : Log all string values in arr.

let arr = [1, 2, 3, 4, "a", "b", "c", "d"] 
let newArr = arr.filter(item => typeof(item) === 'string')

console.log(newArr) // logs ["a", "b", "c", "d"]

12) find(callback)

Returns first value, when the callback returns true.

//Example : Find first string value in arr.

let arr = [1, 2, 3, 4, "a", "b", "c", "d"] 
let value = arr.find(item => typeof(item) === 'string')
console.log(value) // a

13) findIndex(callback)

Returns the first index, when the callback returns true.

//Example : Find first index for string value in arr.

let arr = [1, 2, 3, 4, "a", "b", "c", "d"] 
let index = arr.findIndex(item => typeof(item) === 'string')
console.log(index) // 4

//Example : Find first index for 'a' in arr.

let arr = [1, 2, 3, 4, "a", "b", "c", "d"] 
let index = arr.findIndex(item => item === 'a') 
console.log(index) // 4

I hope this article is useful in your JavaScript learning journey.!

References

developer.mozilla.org/en-US/docs/Web/JavaSc..