Array and Array Methods in JavaScript...

Array and Array Methods in JavaScript...

JavaScript Array

In JavaScript array is a non-primitive data type where we can store an ordered list of values under a single variable name. Each value is called an element and specified by an index. A JavaScript array has the following characteristics -

  • JavaScript arrays can contain a mix of different data types.

  • JavaScript arrays are dynamic and auto-growing or resizable, we don't need to specify the size of the array while declaring an array.

  • JavaScript arrays are zero-indexed. In simple words, the first element of the array is at index 0 and the second element is at index 1 and the last element of the array has an index of the length of the array minus 1.

How to Create Arrays in JavaScript

There are several methods of creating arrays in JavaScript. Here are the most commonly used methods -

  • Using square brackets: This is the most common and straightforward method of creating arrays. Simply declare a variable and assign an array literal to it using square brackets. For example -
const nums = [1, 2, 3, 4, 5];
  • Using the Array constructor: This method allows you to create arrays using the Array constructor. You can pass the length of the array as an argument to the constructor. For example -
const numbers = new Array(5);
  • We can also pass elements to the constructor as arguments, and it will create an array with those elements. For example -
const names = new Array("Apple", "Banana", "Oranges");
  • Using the of method: The of method is a static method of the Array constructor and creates an array from a set of elements. For example -
const characters = Array.of("a", "b", "c");
  • Using the from method: The from method is another static method of the Array constructor and creates an array from an array-like or iterable object. For example -
const letters = Array.from("abcdef");
// This will create an array like this - [ 'a', 'b', 'c', 'd', 'e', 'f' ]
  • Using the fill method: The fill method creates an array of a specified length and fills it with a specified value. For example -
const arr = Array(5).fill(0);
// This will create an array containing five zeros
  • Using the spread operator: The spread operator (...) can be used to spread an iterable object into a new array. For example -
let elements = "abcdef";
const arr = [...elements];
// This will create an array like this - [ 'a', 'b', 'c', 'd', 'e', 'f' ]
  • Using the split method: Using the split method we can create an array from a string. For example -
let elements = "JavaScript is my favorite language";
const arr = elements.split(" ");
// This will create an array like this - [ 'JavaScript', 'is', 'my', 'favorite', 'language' ]

Array Methods

JavaScript Array Methods are built-in functions that provide a way to perform various operations on arrays. Now, before jumping into array methods let's see the array length property and how to access an element of an array. The length property represents the number of elements in an array. For example -

const arr = [1, 2, 3, 4, 5];
console.log(arr.length); // This will print 5 on console as the array has 5 elements so, arr.length = 5.

We can access an element from an array by the index number. Let's take an array arr and we want to access the first element of the array so we can access that by writing this - arr[0] and we can access the last element by using the array length property like this - arr[arr.length - 1].

Now, let's jump into the array methods -

  • push() : The push method in JavaScript is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.
const arr = [1, 2, 3, 4, 5];

// Add an element to the end of the array using push
arr.push(6);
console.log(arr); // [1, 2, 3, 4, 5, 6]

const numbers = [1, 2, 3];

// Add multiple elements to the end of the array using push
numbers.push(4, 5, 6);
console.log(numbers); // [1, 2, 3, 4, 5, 6]
  • pop() : The pop method in JavaScript is used to remove the last element from an array and return that element. It updates the original array.
const numbers = [1, 2, 3];

// Remove the last element from the array using pop
const element = numbers.pop();

console.log(numbers); // [1, 2]
console.log(element); // 3
  • shift() : The shift method in JavaScript is used to remove the first element from an array and return that element. It modifies the original array.
let numbers = [1, 2, 3];

// Remove the first element from the array using shift
let element = numbers.shift();

console.log(numbers); // [2, 3]
console.log(element); // 1
  • unshift() : The unshift method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.
const numbers = [1, 2, 3];

// Add an element to the beginning of the array using unshift
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3]


const numbers = [1, 2, 3];

// Add multiple elements to the beginning of the array using unshift
numbers.unshift(4, 5, 6);
console.log(numbers); // [4, 5, 6, 1, 2, 3]
  • splice() : The splice method in JavaScript is used to add or remove elements from an array at a specific index. It modifies the original array and returns an array containing the removed elements (if any). The syntax of this method is - splice(startIndex, deleteCount) or splice(startIndex, deleteCount, addItem1) or splice(startIndex, deleteCount, addItem1, addItem2,..., addItemN) .
const numbers = [1, 2, 3, 4, 5];

// Remove two elements starting from index 2 using splice
const removed = numbers.splice(2, 2);
console.log(numbers); // [1, 2, 5]
console.log(removed); // [3, 4]


let numbers = [1, 2, 3, 4, 5];

// Add two elements at index 2 using splice
numbers.splice(2, 0, 10, 11);
console.log(numbers); // [1, 2, 10, 11, 3, 4, 5]
  • slice() : The slice method in JavaScript is used to extract a portion of an array and return a new array. It does not modify the original array.
const numbers = [1, 2, 3, 4, 5];

// Get a portion of the array using slice
const arr = numbers.slice(2, 4);

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

In this example, the slice method extracts a portion of the numbers array starting from index 2 up to (but not including) index 4. The extracted portion is returned as a new array ([3, 4]). The original numbers array remains unchanged.

slice can also be used to extract all elements from an array -

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

// Get all elements from the array using slice
const arr = numbers.slice();

console.log(numbers); // [1, 2, 3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
  • sort() : The sort method in JavaScript is used to sort the elements of an array in ascending order by default. It modifies the original array.
const numbers = [3, 1, 5, 4, 2];

// Sort the array using sort
numbers.sort();

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

If we need to sort the elements in descending order, you can use the reverse method with the sort method.

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

// Sort the array in descending order using sort and reverse
numbers.sort().reverse();

console.log(numbers); // [5, 4, 3, 2, 1]
  • reverse() : The reverse method in JavaScript is used to reverse the order of the elements in an array. It modifies the original array.
const numbers = [3, 1, 5, 4, 2];

numbers.reverse();

console.log(numbers); // [ 2, 4, 5, 1, 3 ]
  • indexOf() : The indexOf method in JavaScript is used to search for an element in an array and return its first index. If the element is not found, indexOf returns -1.
const numbers = [1, 2, 3, 4, 5, 3];

// Search for the element 3 using indexOf
const index = numbers.indexOf(3);

console.log(index); // 2

If we want to start the search from a specific index, you can pass a second argument to indexOf. The syntax is indexOf(item, startIndex).

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

// Search for the element 3 starting from index 3 using indexOf
const index = numbers.indexOf(3, 4);

console.log(index); // 5
  • lastIndexOf() : The lastIndexOf method in JavaScript is used to search for an element in an array in reverse order and return its last index. If the element is not found, lastIndexOf returns -1.
const numbers = [1, 2, 3, 4, 5, 3];

// Search for the element 3 using lastIndexOf
const index = numbers.lastIndexOf(3);

console.log(index); // 5

If we want to start the search from a specific index, you can pass a second argument to lastIndexOf. The syntax is lastIndexOf(item, startIndex).

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

// Search for the element 3 starting from index 4 using lastIndexOf
const index = numbers.lastIndexOf(3, 4);

console.log(index); // 2
  • join() : The join method in JavaScript is used to join all elements of an array into a string. The elements are separated by a specified separator (a comma by default).
const numbers = [1, 2, 3, 4, 5];

// Join all elements of the array using join
const str = numbers.join();

console.log(str); // "1,2,3,4,5"

We can also specify a different separator by passing it as an argument to the join method -

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

// Join all elements of the array using join with a separator "-"
const str = numbers.join("-");

console.log(str); // "1-2-3-4-5"
  • concat() : The concat method in JavaScript is used to concatenate two or more arrays into a new array. The original arrays are not modified.
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];

// Concatenate the arrays using concat
const numbers = numbers1.concat(numbers2);

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

We can concatenate more than two arrays as well -

const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const numbers3 = [7, 8, 9];

// Concatenate the arrays using concat
const numbers = numbers1.concat(numbers2, numbers3);

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • forEach() : The forEach method in JavaScript is used to iterate over an array and perform a specific operation on each element of the array.
const numbers = [1, 2, 3, 4, 5];

// Use forEach to log each element of the array
numbers.forEach(element => console.log(element));

// Output:
// 1
// 2
// 3
// 4
// 5

In this example, the forEach method is used to log each element of the numbers array to the console.

The forEach method takes a callback function as an argument. The callback function is invoked for each element of the array and the current element is passed as an argument to the function.

  • map() : The map method in JavaScript is used to create a new array by transforming each element of an existing array.
const numbers = [1, 2, 3, 4, 5];

// Use map to create a new array with each element doubled
const doubled = numbers.map(element => element * 2);

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

In this example, the map method is used to create a new array doubled by transforming each element of the numbers array.

The map method takes a callback function as an argument. The callback function is invoked for each element of the array and the current element is passed as an argument to the function. The return value of the callback function is stored in the new array.

  • filter() : The filter method in JavaScript is used to create a new array by filtering out elements from an existing array that do not meet a specified condition.
const numbers = [1, 2, 3, 4, 5];

// Use filter to create a new array with only even numbers
const evenArray = numbers.filter(element => element % 2 === 0);

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

In this example, the filter method is used to create a new array even by filtering out elements from the numbers array that are not even.

Like the map and forEach, the filter method takes a callback function as an argument. The callback function is invoked for each element of the array and the current element is passed as an argument to the function. If the return value of the callback function is true, the element is included in the new array, otherwise, it is excluded.

  • reduce() : The reduce method in JavaScript is used to reduce an array of elements to a single value. The reduce method takes two arguments - a callback function and an initial value. The callback function is applied to each element of the array, starting from the first element, and the result is accumulated in the initial value.
const numbers = [1, 2, 3, 4, 5];

// Use reduce to calculate the sum of all elements
let sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 15

In this example, the reduce method is used to calculate the sum of all elements of the numbers array.

The reduce method takes two arguments: a callback function and an initial value (0 here).

The callback function takes two arguments: an accumulator and a current value. The accumulator is initialized with the initial value (0) and it is updated with the result of the current iteration on each iteration. The current value is the current element of the array. The return value of the callback function is stored in the accumulator for the next iteration.

These are some of the most commonly used array methods in JavaScript. By using these methods, you can perform a variety of operations on arrays and process data efficiently. There are some other array methods also but I will talk about them some other day.