In 2023 and 2024, JavaScript has seen significant updates with the introduction of several powerful methods that enhance data manipulation and streamline development processes.
Array Grouping
Array Grouping is a method that allows you to group elements of an array based on a given criterion. This can be incredibly useful when you need to categorize data into different groups.
Two methods are offered, Object.groupBy and Map.groupBy. The first returns a null-prototype object, which allows ergonomic destructuring and prevents accidental collisions with global Object properties. The second returns a regular Map instance, which allows grouping on complex key types.
1const transactions = [2 { id: 1, amount: 500, type: 'income', date: '2024-01-15' },3 { id: 2, amount: 100, type: 'expense', date: '2024-01-17' },4 { id: 3, amount: 200, type: 'income', date: '2024-02-10' },5 { id: 4, amount: 50, type: 'expense', date: '2024-02-11' },6 { id: 5, amount: 150, type: 'income', date: '2024-03-05' },7 { id: 6, amount: 75, type: 'expense', date: '2024-03-20' },8 { id: 7, amount: 100, type: 'income', date: '2024-01-25' },9 { id: 8, amount: 60, type: 'expense', date: '2024-02-28' },10];11
12Object.groupBy(transactions, (transaction) => transaction.type);13// -> {income: Array(4), expense: Array(4)}14
15Map.groupBy(transactions, (transaction) => transaction.type);1 collapsed line
16// -> Map(2) {'income' => Array(4), 'expense' => Array(4)}Why is Array Grouping Useful?
- Simplifies Data Organization: Grouping data into meaningful categories can make it easier to process and analyze.
- Reduces Boilerplate Code: No more writing custom grouping functions. The new methods provide a clean, built-in solution.
- Improves Readability: Grouped data structures are often easier to understand and work with.
Useful links
New Array Methods
When using methods like sort(), splice(), and reverse(), the original array is mutated. This can sometimes lead to unintended side effects or issues.
However, with the introduction of methods like toSorted(), toSpliced(), toReversed(), and with(), you can splice, sort, reverse, or replace elements in an array without mutating the original array. These new methods return a new array, leaving the source array unchanged. This approach enhances predictability and prevents inadvertent modifications to your data.
toSorted(compareFn)
The toSorted() method of Array instances is a non-mutating version of the sort() method. It returns a new array with the elements sorted in ascending order, leaving the original array unchanged.
1// Original array of fruits2const fruits = ['banana', 'apple', 'orange', 'grapes'];3
4// Using toSorted() to sort the array without mutating the original array5const sortedFruits = fruits.toSorted();6
7console.log('Original array:', fruits); // -> ["banana", "apple", "orange", "grapes"]8console.log('Sorted array:', sortedFruits); // -> ["apple", "banana", "grapes", "orange"]toSpliced(start, deleteCount, itemN)
The toSpliced() method of Array instances is a non-mutating version of the splice() method. It returns a new array with specific elements removed and/or replaced at a given index, leaving the original array unchanged.
1// Original array of numbers2const numbers = [1, 2, 3, 4, 5];3
4// Using toSpliced() to remove 2 elements starting at index 1, and adding 8 and 95const splicedNumbers = numbers.toSpliced(1, 2, 8, 9);6
7console.log('Original array:', numbers); // -> [1, 2, 3, 4, 5]8console.log('Spliced array:', splicedNumbers); // -> [1, 8, 9, 4, 5]toReversed()
The toReversed() method of Array instances is a non-mutating version of the reverse() method. It returns a new array with the elements in reversed order, while leaving the original array unchanged.
1// Original array of letters2const letters = ['a', 'b', 'c', 'd'];3
4// Using toReversed() to get a reversed copy of the array5const reversedLetters = letters.toReversed();6
7console.log('Original array:', letters); // -> ["a", "b", "c", "d"]8console.log('Reversed array:', reversedLetters); // -> ["d", "c", "b", "a"]with(index, value)
The with() method of Array instances provides a non-mutating alternative to using bracket notation to change the value of a specific index. It returns a new array where the element at the specified index is replaced with the provided value, while leaving the original array unchanged.
1// Original array of fruits2const fruits = ['banana', 'apple', 'orange', 'grapes'];3
4// Using with() to replace an element at a specific index5const replacedFruits = fruits.with(1, 'peach');6
7console.log('Original array:', fruits); // -> ['banana', 'apple', 'orange', 'grapes']8console.log('Array with replaced element:', replacedFruits); // -> ['banana', 'peach', 'orange', 'grapes']Other Array Methods
Let’s explore a few lesser-known methods
at(index)
The at() method of Array instances accepts an integer and retrieves the item located at that index. It supports both positive and negative integers, where negative integers count backward from the last item in the array.
1// Original array of fruits2const fruits = ['banana', 'apple', 'orange', 'grapes'];3
4// Using the at() method to retrieve elements by index5const lastFruit = fruits.at(-1);6const firstFruit = fruits.at(0);7const penultimateFruit = fruits.at(-2);8
9console.log('Fruits array:', fruits); // -> ['banana', 'apple', 'orange', 'grapes']10console.log('Last fruit:', lastFruit); // -> 'grapes'11console.log('First fruit:', firstFruit); // -> 'banana'12console.log('Penultimate fruit:', penultimateFruit); // -> 'orange'findLastIndex(callbackFn)
The findLastIndex() method of Array instances iterates through the array in reverse order and returns the index of the last element that satisfies the provided testing function. If no elements satisfy the testing function, it returns -1.
1// Original array of numbers2const numbers = [5, 12, 50, 130, 44];3
4// Function to check if element is larger than 455const isLargeNumber = (element) => element > 45;6
7// Using findLastIndex() to find the index of the last element greater than 458const lastIndex = numbers.findLastIndex(isLargeNumber);9
10console.log('Array:', numbers); // -> [5, 12, 50, 130, 44]11console.log('Index of last large number:', lastIndex); // -> 312console.log('Value at index 3:', numbers.at(lastIndex)); // -> 130findLast(callbackFn)
The findLast() method of Array instances iterates through the array in reverse order and returns the value of the last element that satisfies the provided testing function. If no elements satisfy the testing function, it returns undefined.
1// Original array of numbers2const numbers = [5, 12, 50, 130, 44];3
4// Using findLast() to find the last element greater than 455const found = numbers.findLast((element) => element > 45);6
7console.log('Array:', numbers); // -> [5, 12, 50, 130, 44]8console.log('Last element greater than 45:', found); // -> 130