Welcome back to the third part of our series on elevating your JavaScript skills through array methods. Having established a solid foundation with simple array methods, we’re now poised to tackle more advanced methods. In this blog, we will discover sophisticated array methods that offer greater flexibility and power in manipulating data. Prepare to unlock new ranges of programming prowess as we continue our deep dive into JavaScript’s array methods. If you haven’t yet, make sure to explore essential array methods in Part 1 and Part 2 of this series.
Advanced array methods encompass a diverse range of categories, each serving specific purposes in data manipulation. These include:
Array Find and Search Methods
Array Sort Methods and Tricks
Array Iteration Methods
These categories provide developers with powerful tools for locating elements, organizing data, and iterating through arrays efficiently, enhancing the capabilities of JavaScript programming.
Array Find and Search Methods
indexOf() and lastIndexOf()
These advanced array methods are like searchlights in the dark, helping you pinpoint the exact location of a specific element within an array. If the element is found, it reveals its index. indexOf() uncovers the first occurrence, while lastIndexOf() reveals the last. However, if the element is nowhere to be found, they report back -1, indicating that the search was unsuccessful.
Example:
const animals = [“Cheetah”, “Lion”, “Zebra”, “Horse”, “Cheetah”, “Deer”];
const firstIndex = animals.indexOf(“Cheetah”);
console.log(“firstIndex”, firstIndex);
const lastIndex = animals.lastIndexOf(“Cheetah”);
console.log(“lastIndex”, lastIndex);
Output:
includes()
It is used to determine whether a value is included in the system entry and returns true or false as appropriate.
Example:
const colors = [‘red’, ‘green’, ‘blue’];
console.log(“includes method:”)
console.log(colors.includes(‘green’));
console.log(colors.includes(‘yellow’));
Output:
find() and findIndex()
find()
This function helps find the first array element that meets a condition. If found, it returns the element; otherwise, it is undefined.
Example:
const movies = [“The Lion King”, “Aladdin”, “The Jungle Book”, “Moana”];
const foundMovie = movies.find((movie) => movie === “Aladdin”);
console.log(“find method:n”, foundMovie);
Output:
findIndex()
It returns the index of the first element in the array that satisfies the given testing function. If the function does not satisfy any element, it will return -1.
Example:
const movies = [“The Lion King”, “Aladdin”, “The Jungle Book”, “Moana”];
const index = movies.findIndex((movie) => movie === “Moana”);
console.log(“findIndex method:n”, index);
Output:
findLast()
This method fetches the last array element that meets the condition set by the provided testing function.
Example:
const numbers = [10, 20, 30, 40, 50];
const lastNumber = numbers.findLast(num => num > 20);
console.log(“Output:”,lastNumber);
Output:
findLastIndex()
It retrieves the index of the last array element that fulfills the conditions set by the testing function.
Example:
const numbers = [10, 20, 30, 40, 50];
const lastIndex = numbers.findLastIndex(num => num > 20);
console.log(“Last index of matched condition:”,lastIndex); // Output: 4 (index of 50)
Output:
Array Iteration Methods
forEach()
It’s like having a guide show you around a museum, stopping at each exhibit along the way. method executes a function for every element within an array.
Example:
const numbers = [1, 2, 3, 4, 5];
console.log(“forEach method:”)
numbers.forEach((num) => console.log(num * 2));
Output:
flat() and flatMap()
flat()
Imagine you have a stack of nested trays, each containing some items. flat() is like taking out all the items from those trays and putting them into a single tray, simplifying the organization.
Example:
const nestedArray = [[“Peter Pan”, “Aladdin”], [“Mulan”, “Maleficent”], [“Moana”, “Tangled”]];
const flattenedArray = nestedArray.flat();
console.log(“flat method:n”,flattenedArray);
Output:
flatMap()
It’s like having a stack of notebooks, and you need to examine each page, write something on it, and then gather all those pages into a new notebook. flatMap() first maps over every element inside the array using a function you offer and then flattens the result into a new array, making it easier to deal with.
Example:
const numbers = [1, 2, 3];
const mappedAndFlattened = numbers.flatMap(num => [num * 2, num * 3]);
console.log(“flatMap:n”,mappedAndFlattened);
Output:
filter()
Think of it as a filter on a coffee machine that separates ground coffee from brewed coffee, ensuring that only pure water flows in. Filter() in JavaScript searches each element of an array to establish a condition specifically, storing only those elements that satisfy the condition and using those elements to create a new array.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(“filter method:n”, evenNumbers);
Output:
every() and some()
These methods are like gatekeepers, checking each element against a condition.
every():
The condition is checked if all elements are met.
Example:
const numbers = [2, 4, 6, 7, 8];
const allEven = numbers.every((num) => num % 2 === 0);
console.log(“every method:n”, allEven);
output:
some():
Checks if at least one element meets a condition.
Example:
const numbers = [2, 4, 6, 7, 8];
const anyEven = numbers.some((num) => num % 2 === 0);
console.log(“some method:n”, anyEven);
Output:
reduce():
It’s like having a calculator that provides all the numbers in a list for you. You provide a function that tells the calculator a way to combine every range with the running total.
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, current) => total + current, 0);
console.log(“reduce method:n”,sum);
Output:
Example 2:
const items = [
{ name: “Shirt”, price: 20 },
{ name: “Pants”, price: 30 },
{ name: “Shoes”, price: 50 },
];
const totalPrice = items.reduce((acc, item) => acc + item.price, 0);
console.log(“reduce method:”);
console.log(“Total Price:”, totalPrice);
Output:
reduceRight()
The function reduces each value of the array (from right to left) against an accumulator to produce a single value.
Example:
const arr = [1, 2, 3, 4];
const sum = arr.reduceRight((accumulator, currentValue) => accumulator + currentValue);
console.log(“Sum of all numbers:”,sum); // Output: 10 (4 + 3 + 2 + 1)
Output:
Array Sort Methods
1. Array Alphabetic Sort
sort():
The elements of an array are sorted in place by the sort() method, and the sorted array is returned. It rearranges elements either in place or by creating a new sorted array.
Example:
const numbers = [36, 17, 84, 01, 65, 19, 22, 16];
const sortedNumbers = numbers.sort();
console.log(“sort method:n”,sortedNumbers)
output:
reverse()
reverse() The order of the elements in the array is reversed. It’s like looking at a mirror image of your array. Moves an array to its location and returns a reference to the same array; the first array element is now the last, and the last array element is the first.
Example:
const animals = [“Cheetah”, “Lion”, “Zebra”, “Horse”, “Deer”];
animals.reverse();
console.log(“reverse method:”);
console.log(“Array in reverse order:”, animals);
Output:
toSorted()
The array is returned with elements sorted in ascending order.
Example:
const numbers = [5, 2, 8, 1, 4];
const sortedNumbers = numbers.toSorted();
console.log(“Sorted in ascending order”,sortedNumbers);
Output:
toReversed()
Returns the array with elements in reverse order.
Example:
const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = numbers.toReversed();
console.log(“Elements in reverse order:”,reversedNumbers);
Output:
2. Array Numeric Sort
Math.min()
The smallest number among the provided arguments is returned.
Example:
const minNumber = Math.min(22,15,34);
console.log(“Smallest number in the series:”,minNumber);
Output:
Math.max()
The function determines the largest number among the arguments provided.
Example:
const maxNumber = Math.max(10, 45, 20);
console.log(“Largest number in the series:”,maxNumber);
Output:
Conclusion
Our exploration of JavaScript array methods has led us from fundamental operations to more advanced techniques. These tools empower developers to manipulate data efficiently and think critically about problem-solving in JavaScript. By mastering these methods, you’ll enhance your coding skills and uncover deeper layers of JavaScript’s potential. Keep practicing and experimenting to unlock even greater possibilities in your coding journey. For those who started here, consider revisiting Essential Methods Part 1 and Part 2 to ensure a comprehensive understanding of array basics.
Source: Read MoreÂ