Array and its methods in JavaScript

Array and its methods in JavaScript

·

6 min read

Array

In JavaScript array is a special variable, which can hold more than one value like a number, string, boolean etc as a single variable. Arrays are represented by a pair of square brackets ["Array"]. The values inside an array are known as elements. Each element in an array is separated by commas ,.

Creating an Array

To create an array in JavaScript, you can use either the array literal syntax or the Array() constructor. The array literal syntax is the most common and preferred way. Here's an example of creating an array using both methods:

// Array literal syntax
let numbers = [1, 2, 3, 4, 5];

// Array constructor
let colors = new Array('red', 'green', 'blue');

Accessing Array Elements

Individual elements in an array are accessed using their index. In JavaScript, array indices start from 0, so the first element is at index 0, the second element is at index 1, and so on.

Capture.JPG

push()

The push() method allows you 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. Let's consider an example:

const fruits = ['apple', 'banana', 'orange'];
const newLength = fruits.push('kiwi', 'mango');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'kiwi', 'mango']
console.log(newLength); // Output: 5

pop()

pop() method removes the last element from an array, reducing its length by one. It returns the removed element. Here's an example:

const fruits = ['apple', 'banana', 'orange'];
const removedElement = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(removedElement); // Output: 'orange'

shift()

The shift() method removes the first element from an array and shifts all other elements down, updating the length of the array. It returns the removed element. Let's see an example:

const fruits = ['apple', 'banana', 'orange'];
const removedElement = fruits.shift();
console.log(fruits); // Output: ['banana', 'orange']
console.log(removedElement); // Output: 'apple'

unshift()

unshift() inserts one or more elements at the beginning of an array, pushing existing elements to higher indexes. It returns the new length of the array. Consider the following example:

const fruits = ['banana', 'orange'];
const newLength = fruits.unshift('apple', 'kiwi');
console.log(fruits); // Output: ['apple', 'kiwi', 'banana', 'orange']
console.log(newLength); // Output: 4

slice()

The slice() method returns a shallow copy of a portion of an array into a new array, without modifying the original array. It takes two optional arguments: the starting and ending index. Here's an example:

const fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango'];
const slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits); // Output: ['banana', 'orange', 'kiwi']

splice() The splice() method allows you to add, remove, or replace elements in an array. It modifies the original array and returns the removed elements as a new array. The first argument specifies the starting index, the second argument indicates how many elements to remove, and additional arguments can be used to add elements. Let's consider an example:

const fruits = ['apple', 'banana', 'orange'];
const removedElements = fruits.splice(1, 1, 'kiwi', 'mango');
console.log(fruits); // Output: ['apple', 'kiwi', 'mango', 'orange']
console.log(removedElements); // Output: ['banana']

find()

The find() method allows you to search for the first element in an array that satisfies a given condition. It takes a callback function as an argument, which is executed for each element until a match is found. Once a matching element is identified, find() returns that element, or undefined if no match is found. Here's an example:

const numbers = [10, 25, 5, 30, 15];
const result = numbers.find((number) => number > 20);

console.log(result); // Output: 25

In this example, find() searches through the numbers array and returns the first element that is greater than 20.

filter()

The filter() method creates a new array consisting of all elements that satisfy a specified condition. It takes a callback function similar to find(), but instead of returning a single element, filter() returns an array of matching elements. If no elements meet the condition, an empty array is returned. Consider the following example:

const numbers = [10, 25, 5, 30, 15];
const result = numbers.filter((number) => number > 20);

console.log(result); // Output: [25, 30, 15]

In this case, filter() creates a new array containing all elements greater than 20 from the numbers array.

includes()

The includes() method determines whether an array includes a specific value and returns a boolean value accordingly. It checks if the array contains the specified element and returns true if found, or false otherwise. Here's an example:

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.includes('banana');

console.log(result); // Output: true

In this example, includes() checks whether the fruits array contains the value 'banana' and returns true.

map()

map() method transforms each element of an array and returns a new array with the modified values. For example:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((num) => num * 2);
// Output: [2, 4, 6, 8, 10]
  • indexOf()* indexOf() method searches an array for a specific element and returns its index. If the element is not found, it returns -1. Example:
const fruits = ['apple', 'banana', 'orange'];
const index = fruits.indexOf('banana');
// Output: 1

sort()

sort() method arranges the elements of an array in ascending order by default. It performs a comparison between elements and reorders them accordingly. sort() do not return a new array but modify the original array directly. Here's an example:

const numbers = [5, 2, 8, 1, 4];
numbers.sort();

console.log(numbers); // Output: [1, 2, 4, 5, 8]

In the example above, the sort() method is applied to the numbers array, resulting in the elements being sorted in ascending order.

To sort elements in descending order or based on a specific condition, you can provide a comparison function to the sort() method. This function determines the sorting order by returning negative, zero, or positive values. Here's an example:

const numbers = [5, 2, 8, 1, 4];
numbers.sort((a, b) => b - a);

console.log(numbers); // Output: [8, 5, 4, 2, 1]

In this case, the comparison function (a, b) => b - a sorts the numbers array in descending order.

reverse()

The reverse() method reverses the order of elements in an array, providing a straightforward way to invert the array's sequence. Here's an example:

const fruits = ['apple', 'banana', 'orange'];
fruits.reverse();

console.log(fruits); // Output: ['orange', 'banana', 'apple']

In this example, the reverse() method is applied to the fruits array, resulting in the elements being reversed.

reverse() modify the original array directly and do not return a new array.

contact()

The concat() method merges two or more arrays, creating a new array that contains the combined elements. It does not modify the original arrays but rather returns a new array. Here's an example:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newArray = array1.concat(array2);

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

concat() methods can also be used to add individual elements or other data types to an existing array. For example:

const array = [1, 2];
const newArray = array.concat(3, 4, [5, 6]);

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

In this case, concat() is used to add the elements 3 and 4, as well as the array [5, 6], to the array.

join()

The join() method converts the elements of an array into a string by concatenating them with a specified separator. By default, the separator is a comma. For example:

const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(', ');

console.log(result); // Output: "apple, banana, orange"
const numbers = [1, 2, 3];
const result = numbers.join('-');

console.log(result); // Output: "1-2-3"

In conclusion, arrays are a fundamental part of JavaScript, providing developers with powerful tools to store, manipulate, and iterate over collections of data. JavaScript offers a rich set of built-in array methods that make it easier to perform common operations efficiently.

References: