We’ll explore a variety of key array methods, acquiring understanding through practical examples. To maintain relevance and context, we’ll concentrate on manipulating an array that holds a list of employees.
Here is the array containing our employee list:
let employees = ['John Doe', 'Jane Smith', 'Mike Jordan'];
By the end of this article, you will have a more precise and practical understanding of all essential array methods, equipping you with the skills to manipulate arrays effectively in various scenarios.
1. .push() – Adding Elements to the End
.push() method is used to append new elements to the end of an existing array and returns the new length of the array.
// Orignal Array: ['John Doe', 'Jane Smith', 'Mike Jordan'] employees.push('Sarah Connor'); // Result: ['John Doe', 'Jane Smith', 'Mike Jordan', 'Sarah Connor']
In this example, 'Sarah Connor' is appended to the 'employees' array. The updated array, now containing 'Sarah Connor' as the last element, is returned as the result.
2. .pop() – Removing the Final Element
.pop() method is used to both retrieve and remove the last element of an array.
Here's an example:
// Original Array : ['John Doe', 'Jane Smith', 'Mike Jordan', 'Sarah Connor'] let removedEmployee = employees.pop(); // Result: 'Sarah Connor'; // Updated Array: ['John Doe', 'Jane Smith', 'Mike Jordan']
In this example,
removedEmployee stores the last element, 'Sarah Connor', from the
employees array while simultaneously removing it from the original array, resulting in the modified array with the remaining elements.
3. shift() – Extracting the Initial Element
In contrast to
.pop() method, the
.shift() method purges and returns the array's first element.
// Original Array: ['John Doe', 'Jane Smith', 'Mike Jordan'] let initialEmployee = employees.shift(); // Result: 'John Doe'; // Modified Array: ['Jane Smith', 'Mike Jordan']
In this case, the
initialEmployee the variable will hold the value 'John Doe', and the
employees the array will be updated with the remaining elements.
4. .unshift() – Adding Elements to the beginning of an array
.unshift() method is used to insert a new element at the start of the array and returns the revised array as the result.
// Orignal Array: ['Jane Smith', 'Mike Jordan'] employees.unshift('Samuel L. Jackson'); // Result: ['Samuel L. Jackson', 'Jane Smith', 'Mike Jordan']
In this example, 'Samuel L. Jackson' has been added to the beginning of the 'employees' array, making it the first element of the array. The modified array is then returned, showing 'Samuel L. Jackson' as the new first element, followed by the original elements.
5. .map() – To transform array elements
.map() method applies a provided function to each element in the array and returns a new array containing the results.
Consider the following example with
.map() method to transform each employee's name to uppercase:
// Orignal Array: ['Samuel L. Jackson', 'Jane Smith', 'Mike Jordan'] let employeesTransformed = employees.map(employee => employee.toUpperCase()); // Result: ['SAMUEL L. JACKSON', 'JANE SMITH', 'MIKE JORDAN']
Additional Examples of .map() method:
Here are a few more examples demonstrating the practical usage of the
.map() method to transform array elements:
- Converting Numbers to Their Squares:
let numbers = [1, 2, 3]; let squaredNumbers = numbers.map(number => number * number); // Result: [1, 4, 9]
- Appending Text to Strings in an Array:
let fruits = ['apple', 'banana', 'cherry']; let modifiedFruits = fruits.map(fruit => fruit + ' is delicious'); // Result: ['apple is delicious', 'banana is delicious', 'cherry is delicious']
- Calculating the Length of Strings in an Array:
let words = ['elephant', 'dolphin', 'giraffe']; let wordLengths = words.map(word => word.length); // Result: [8, 7, 7]
6. .filter() – Selecting Elements
.filter() method is used to filter elements in an array based on defined criteria.
let employeesWithLongNames = employees.filter(employee => employee.length > 12); // Result: ['Samuel L. Jackson', 'Mike Jordan']
This method creates a new array with all elements that pass the test implemented by the provided function. For instance, in the example above, it filters out the employees whose names have more than twelve characters.
Additional Examples of filter() method:
// Filtering out even numbers from an array of numbers let numbers = [1, 2, 3, 4, 5, 6]; let evenNumbers = numbers.filter(num => num % 2 === 0); // Result: [2, 4, 6] // Filtering out fruits with more than 5 letters in their name from an array of fruits let fruits = ['apple', 'banana', 'kiwi', 'grape']; let longNameFruits = fruits.filter(fruit => fruit.length > 5); // Output: ['banana']
7. .reduce() – Consolidating Array Elements to a Singular Value
.reduce() method allows you to consolidate or condense all the elements in an array into a single value, using the provided function. This method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Here’s an example to demonstrate the functionality of the
Suppose you have an array of employee names, and you would like to create a single string that contains all those names, separated by a comma. This can be achieved using the
.reduce() the method as follows:
let accumulatedEmployeeNames = employees.reduce((accumulatedList, currentEmployee) => accumulatedList + ', ' + currentEmployee); // Result: 'Samuel L. Jackson, Jane Smith, Mike Jordan'
In this example,
accumulatedList is the accumulating parameter holding the continually concatenated string of employee names, and
currentEmployee is the current element being processed in the array. The method goes through each element in the array, appending each employee name to the, resulting in a string that combines all the employee names from the original array.
8. .find() – Search within the array
.find() method returns the value of the first element in the provided array that satisfies the provided testing function. This is extremely helpful when you want to retrieve a specific item from a collection based on certain criteria.
Here’s an example to understand the usage of
Assume you have a list of employees, and you want to find the first one whose name includes ‘Smith’. You can achieve this as follows:
let employee = employees.find(employee => employee.includes('Smith')); // Output: 'Jane Smith'
In this scenario,
employee will hold the value 'Jane Smith', as it’s the first element in the array of employees that meets the criteria.
9. .indexOf() – Find the Index of an Element
.indexOf() method is handy when you need to find the position of a specific element in an array. It returns the index of the first occurrence of the specified element. If the element is not found, it returns -1.
Here's an example to find the index of an employee named
Mike Jordan in the
let employees = ['John Doe', 'Jane Smith', 'Mike Jordan', 'Sara Connor']; let indexPosition = employees.indexOf('Mike Jordan'); // The returned value will be 2.
In this scenario, we're searching for the element 'Mike Jordan' within the
employees array. Since arrays are zero-indexed, 'Mike Jordan', being the third element in the array, is at index 2. If we were to search for an employee not listed in the array, the returned value would be -1, indicating the element is not present in the array. For example:
let missingEmployeeIndex = employees.indexOf('Sam Winchester'); // The returned value will be -1 since 'Sam Winchester' is not present in the array.