Common Array Methods

Arrays in JavaScript come with a variety of built-in methods that make it easy to manipulate and work with collections of data. These methods allow you to add, remove, or modify elements in an array without needing to manually manage the data. Let's dive into some of the most commonly used array methods.

push() method

Adds one or more elements to the end of an array.

Syntax

javascript
1
          arrayName.push(element1, element2, element3);
        

To use this method:

  • writing the name of the array
  • then dot (.)
  • then writing the name of the method (push) followed by parentheses
  • inside these parentheses we pass the elements that we want to add to the end of the array as arguments.

Example

javascript
1
2
3
4
5
            let fruits = ['apple', 'banana'];

  fruits.push('orange'); // Adds 'orange' to the end

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

pop() method

Removes the last element from an array and returns the deleted element.

Syntax

javascript
1
          arrayName.pop();
        

This method can be used by writing the name of the array, then dot, then writing the name of the method (pop) followed by parentheses.

Note: This method does not take any parameters.

javascript
1
2
3
4
5
6
7
            let fruits = ['apple', 'banana', 'orange'];

  let removedFruit = fruits.pop(); // Removes 'orange'

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

  console.log(removedFruit); // 'orange'
        

unshift() method

Adds one or more elements to the beginning of an array.

Syntax

javascript
1
          arrayName.ushift(element1, element2, element3);
        
javascript
1
2
3
4
5
            let fruits = ['banana', 'orange'];

  fruits.unshift('apple'); // Adds 'apple' to the start

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

shift() method

Removes the first element from an array and returns it.

Syntax

javascript
1
          arrayName.shift();
        
javascript
1
2
3
4
5
6
7
            let fruits = ['apple', 'banana', 'orange'];

  let removedFruit = fruits.shift(); // Removes 'apple'

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

  console.log(removedFruit); // 'apple'
        

These methods are useful when you need to modify the array by adding or removing items at the start or the end.

IndexOf() method

  • This method searches for a specific value inside an array.
  • Returns the first occurrence index of the value you are looking for.
  • It returns -1 if the element is not present in the array.

Syntax

javascript
1
          arrayName.indexOf(searchElement, fromIndex)
        

This method take two parameters

  1. 1
    The first parameter (Required) is searchElement: The value you want to search for in the array.
  2. 2
    The second parameter (optional) is fromIndex: The index from which to start the search.

Note: If you don't specify an index to start the search from, the search will start from index 0. Because the default value is 0

To use this method:

  • Write the name of the array
  • then dot (.)
  • then writing the name of the method (indexOf) followed by parentheses
  • inside the parentheses we pass the value we want to search for inside the array as the first argument. and we pass The index from which to start the search as the second argument.

Examples:

javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad'];

console.log(menu.indexOf('Meat')); // This line searches for a Meat value inside the array. It returns the index number of the element inside the array and prints it to the console.
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad'];

console.log(menu.indexOf('Bread')); // Output: -1, -1 because the value I am looking for does not exist.
        
javascript
1
2
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];
console.log(menu.indexOf('Rice')); // Output: 2,  2 because returns the first occurrence index of the value you are looking for
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.indexOf('Rice', 3)); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console. Search starts from index 3.
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.indexOf('Rice', -1)); // This line searches for a Rice value inside the array. It returns the index number of the element inside the array and prints it to the console. Search starts from index -1.
        

Note: index -1 is the last element in the array.

lastIndexOf() method

  • This method searches for a specific value inside an array, starting from right to left, Returns the first occurrence index of the value you are looking for.
  • It returns -1 if the element is not present in the array.

Syntax

javascript
1
          arrayName.lastIndexOf(searchValue, fromIndex);
        

This method take two parameters

  1. 1
    The first parameter (Required) is searchValue: The value you want to search for in the array.
  2. 2
    The second parameter (optional) is fromIndex: The index from which to start the search.

Note: If you don't specify an index to start the search from, the search will start from the last index in the array.

Examples:

javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.lastIndexOf('Rice')); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console.
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.lastIndexOf('Rice', -2)); // This line searches for a Rice value inside the array. It returns the index of the element inside the array and prints it to the console.
        

Note:

  • -1 is the last element in the array or the first element from the right in the array.
  • -2 is the second element from the right in the array.
  • -3 is the third element from the right in the array and so on.

includes() method

  • The includes() method is a built-in JavaScript function used to check for the existence of a specific element within the array.
  • Returns true if the specified value you are looking for is found in the array.
  • Returns false if the value you are looking for is not found in the array.

Syntax

javascript
1
          arrayName.includes(searchElement, fromIndex);
        

This method takes two parameters:

  1. 1
    The first parameter is searchElement(Required): The value you are searching for in the array..
  2. 2
    The second parameter is fromIndex(optional): The index from which the search begins. The default is 0

Examples: Basic Usage:

javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.includes('Rice')); // Output: true
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.includes('Bread')); // Output: false
        

If we look at these examples, we find that

  • The first line of the code is an array containing several elements.
  • The second example checks if 'Rice' exists in the array using the includes method. The result is true because 'Rice' is in the array.
  • The third example checks for 'Bread'. The result is false because 'Bread' is not in the array.

Examples: Using the fromIndex parameter

javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.includes('Rice', 2)); // Output: true
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.includes('Chicken', 2)); // Output: false
        
javascript
1
2
3
          let menu = ['Fish', 'Chicken', 'Rice', 'Meat', 'Salad', 'Rice'];

console.log(menu.includes('rice', 2)); // Output: false
        

If we look at these examples, we find that

  • The first line of the code is an array containing several elements.
  • menu.includes('Rice', 2): Searches for 'Rice' starting from index 2 using the includes method. The result is true because 'Rice' is found at index 2.
  • menu.includes('Chicken', 2): Searches for 'Chicken' starting from index 2 using the includes method. The result is false because 'Chicken' occurs before index 2.
  • menu.includes('rice', 2): Searches for 'rice' (lowercase) starting from index 2 using the includes method. The result is false because the search is case-sensitive.

Notes

  • The includes() method is case-sensitive: 'Rice' and 'rice' are treated as different values.
  • If the fromIndex parameter is negative, the search starts from the array's length plus the negative value.

Reverse Method

The reverse() method is a built-in function for arrays that reverses the order of the elements in an array in place. This means the original array is modified, and the elements are reordered such that the first element becomes the last, the second becomes before the last, and so on.

Syntax

javascript
1
          arrayName.reverse();
        

Example:

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

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

slice() method

Creates a new array by extracting a portion of an array. It doesn't modify the original array.

Syntax

javascript
1
          arrayName.slice(startIndex, endIndex);
        

This method takes two parameters:

  1. 1
    The first parameter (optional) is start: The index at which the extraction begins.
  2. 2
    The second parameter (optional) is end: The index at which to end extraction (exclusive). The elements up to, but not including

Note: If we don't write the first parameter (startIndex), the default value will be set to 0 (the beginning of the array).

Note: If we do not write the second parameter (EndIndex), the default value is the length of the array (extracting all elements to the end).

javascript
1
2
3
4
5
6
7
            let fruits = ['apple', 'banana', 'orange', 'pear'];

  let slicedFruits = fruits.slice(1, 3); // Extracts from index 1 to 3 (not including 3)

  console.log(slicedFruits); // ['banana', 'orange']

  console.log(fruits); // Original array remains unchanged
        

You can use slice() to create a new array with a specific range of elements.

splice() method

The splice() method is used to add, remove, or replace elements in an array. It directly modifies the original array and returns an array of the removed elements.

Syntax:

javascript
1
          array.splice(startIndex, deleteCount, item1, item2, ...)
        

Parameters:

startIndex (required):

  • The index at which to start changing the array
  • If negative, it counts from the end of the array (-1 = last element)

deleteCount (optional):

  • Number of elements to remove from the array
  • If 0 or omitted, no elements are removed
  • If greater than remaining elements, all elements from startIndex onward are removed

item1, item2, ... (optional):

  • Items to add to the array starting at startIndex.
  • If not provided, splice() will only remove elements

Return Value

  • Returns an array containing the deleted elements.
  • If no elements are removed, returns an empty array.

Examples:

1. Remove elements

javascript
1
2
3
4
5
6
7
          let fruits = ["apple", "banana", "cherry", "date"];

let removed = fruits.splice(1, 2); // Removes 2 elements starting at index 1

console.log(fruits); // Output: ["apple", "date"]

console.log(removed); // Output: ["banana", "cherry"]
        

2. Add elements

javascript
1
2
3
4
5
          let colors = ["red", "blue"];

colors.splice(1, 0, "green", "yellow"); // Add at index 1 without deleting

console.log(colors); // Output: ["red", "green", "yellow", "blue"]
        

3. Replace elements

javascript
1
2
3
4
5
          let nums = [1, 2, 3, 4];

nums.splice(1, 2, 9, 8); // Replace 2 elements at index 1 with 9 and 8

console.log(nums); // Output: [1, 9, 8, 4]
        

4. Using Negative Index

javascript
1
2
3
4
          const letters = ['a', 'b', 'c', 'd'];
letters.splice(-2, 1); // Removes 'c' (2nd from end)

console.log(letters); // Output: ['a', 'b', 'd']
        

Notes:

  • splice() modifies the original array (unlike slice() which returns a new array).
  • Returns an array of deleted elements (can be empty).
  • If deleteCount is 0, it just inserts without removing.
  • For large arrays, splice() can be less efficient than creating a new array since it requires reindexing

The splice() method is extremely versatile and is one of the most useful array manipulation methods in JavaScript.

sort() method

The sort() method is used to sort the elements of an array in place (modifying the original array) and returns the sorted array.

Syntax

javascript
1
          array.sort([compareFunction]);
        

Parameters

compareFunction (optional):

  • A function that defines the sort order.
  • If omitted, the array elements are converted to strings and sorted lexicographically (dictionary order)

Return Value

The sorted array (note that the original array is modified)

Examples

Default Behavior (No compareFunction)

When no compare function is provided:

  • Elements are converted to strings.
  • Sorted based on their UTF-16 code unit values.
  • This can lead to unexpected results with numbers.
javascript
1
2
3
4
5
6
7
          const fruits = ['banana', 'Apple', 'cherry'];
fruits.sort();
console.log(fruits); // Output: ['Apple', 'banana', 'cherry'] (case-sensitive)

const numbers = [10, 2, 1, 20];
numbers.sort();
console.log(numbers); // Output: [1, 10, 2, 20] (lexicographical order)
        

Using compareFunction

To properly sort numbers or define custom sort orders:

javascript
1
2
3
4
5
6
          array.sort((a, b) => {
  // Return value meaning:
  // < 0: a comes before b
  // 0: keep original order
  // > 0: b comes before a
});
        

Common Compare Functions

1. Sorting numbers (ascending):

javascript
1
2
3
          const numbers = [10, 2, 1, 20];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 10, 20]
        

2. Sorting numbers (descending):

javascript
1
2
3
          const numbers = [10, 2, 1, 20];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [20, 10, 2, 1]
        

3. Sorting objects by property:

javascript
1
2
3
4
5
6
7
8
9
10
11
          const users = [
  { name: 'John', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 20 }
];

// Sort by age (ascending)
console.log(users.sort((a, b) => a.age - b.age));

// Sort by name (alphabetical)
console.log(users.sort((a, b) => a.name.localeCompare(b.name)));
        

Notes:

  • sort() modifies the original array (mutates it).
  • For case-insensitive string sorting:
javascript
1
2
          const words = ['Apple', 'banana', 'cherry'];
console.log(words.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())));
        
  • For stable sorting (maintaining original order of equal elements):
  • 1. Modern JavaScript engines implement stable sorting.
  • 2. Older implementations might not be stable.

Performance Considerations

  • The time and space complexity of sort is implementation-dependent.
  • Modern engines use O(n log n) algorithms like TimSort.
  • For very large arrays, consider performance implications.

Example with Mixed Data

javascript
1
2
3
          const mixed = [10, '2', '1', 20, '10'];

console.log(mixed.sort()); // Output: ['1', '10', 10, '2', 20] (string comparison)
        
javascript
1
2
3
          const mixed = [10, '2', '1', 20, '10'];

console.log(mixed.sort((a, b) => a - b)); // Output: ['1', '2', 10, '10', 20] (numeric)
        

The sort() method is powerful but requires careful use, especially with the compare function, to get the desired results.

Chaining Methods

Many of the array methods can be chained together, meaning you can use one method immediately after another in a single line of code. This is often used for cleaner and more readable code.

javascript
1
2
3
4
5
6
7
          let numbers = [1, 2, 3, 4, 5];
let result = numbers
  .map(num => num * 2) // Multiplies each number by 2
  .filter(num => num > 5) // Filters out numbers less than or equal to 5
  .reduce((sum, num) => sum + num, 0); // Adds up all the numbers

console.log(result); // 18 (6 + 8 + 10)
        

In this example, the methods map(), filter(), and reduce() are chained together to transform and process the data in one go.

Array methods are powerful tools for manipulating and working with data. They help you perform common tasks with ease and, when used in combination, can make your code more efficient and readable.