6 Must know Javascript array methods You missed in 2023
Tags: javascript, typescript, node
Published: 2023-12-22 20:45:23

While most developers were busy getting high on the AI drug, Javascript has made huge strides in keeping updated with the latest development trends. Every major Tech firm is releasing a product or service that deals with AI in some way or another with some companies just using it, (AI) as a Marketing glitch. While many awesome features were added to our most beloved programming language Javascript in 2023, my concern for today is the new Javascript array methods you missed while worrying about when AI will take over your job.

If you like me prefer a functional approach to programming then you are familiar with some mutable array methods in Javascript and the little irritating bugs they can produce, sorting an array in Javascript will mutate the original array, and this behavior is not always desired because it messes with the flow of the code in your head and makes those bugs just more difficult to track. We are well aware of how difficult it is to get the last occurrence of an item in an array, you had to write some hack that looks like a spell from a 16th-century witchcraft book, the fact that you had to write a gimmick to get the last occurrence of an item in an array in more witchcraft than we can craft with Javascript.

In today's post, I'm going to discuss all the new Array prototype methods that were added to Javascript and how they can greatly simplify array manipulation and allow us to write less buggy code that adheres to true functional programming due to the immutability of the new array methods. We will consider the following talking points.

- Immutable Sort
- Immutable Reverse
- Immutable Splice
- Find the Last Item
- No more index mutations

## Immutable sort

Javascript has decided to make life easier for developers by providing a new method that allows us to sort an array without having to mutate the array. The method will instead create a sorted copy of the original array. This is the `array.prototype.toSorted()` and this method works very much like `array.prototype.sort()`. The only difference between the two of them lies in the fact that `sorted ()` will not mutate the original array, rather it will return a sorted copy, but `sort` will mutate the original.

```typescript
const array = [0, 8, 3, 5, 1, 9, 7];

// using array.sort()
const sortedArray = array.sort();
console.log(sortedArray) 
// [ 0, 1, 3, 5, 7, 8, 9 ]
cosnole.log(array)
// [ 0, 1, 3, 5, 7, 8, 9 ]
```

You can see from the snippet above that calling `array.sort()` also mutates the original array and this behavior is like having to go to work on a rainy day. What if you still have to use the array in its original state after you've sorted it? You now have to start thinking of unholy solutions to the situation, whereas with `toSorted` you will get a different behavior.

```typescript
const array = [0, 8, 3, 5, 1, 9, 7];

// using array.toSorted()
const _sortedArray = array.toSorted();
console.log(_sortedArray)
// [ 0, 1, 3, 5, 7, 8, 9 ]
console.log(array)
// [0, 8, 3, 5, 1, 9, 7]
```

From the snippet we have above you can see that the original array was not mutated and its state is preserved, thus ridding us of the need to worry about preserving its state manually. This gives us so much freedom and less concern when sorting arrays. Allowing us to follow proper functional programming principles. If we extract the above codebase into a function that accepts an array as its argument and returns a sorted copy of the array as its argument. We can be sure that given the same input, our code will always produce the same output.

## Immutable Reverse

To be entirely honest with you, rarely have I ever needed to reverse an array. But if you do some 10X developing then you might need to. We had the `array.reverse()` method for reversing an array in Javascript. This method like the `sort()` method we just discussed above will mutate the original array and we've already established that this behavior is not always desired. Thus we now have the `array.toReversed()` which reverses an array but instead of mutating the value of the original array, it is going to return a revered copy of the original array.

```typescript
const array = [0, 1, 2, 3, 4];

// using array.sort()
const reversedArray = array.reverse();

console.log(reversedArray) 
// [ 4, 3, 2, 1, 0 ]
console.log(array)
// [ 4, 3, 2, 1, 0 ]
```

The snippet above demonstrates the undesired behavior of mutating the original array when we call `array.reverse`, thank God we now have the `toReversed()` method which rids us of the need for any weird hack to get around this behavior.

```typescript
const array = [0, 1, 2, 3, 4];
const reversedArray = array.toReversed();

console.log(reversedArray);
// [ 4, 3, 2, 1, 0 ]
console.log(array);
 [0, 1, 2, 3, 4];
```

## Immutable Splice

If you call the `splice` method on an array in Javascript it will behave like the other two methods we just discussed, it will mutate the original array. The `splice` method is used to change the content of an array by either replacing, removing, or adding new elements to the array. It's a handy way to insert, update, or delete a value from a particular index in an array.

```typescript
const array = ["Mon", "Wed", "Thurs"];

array.splice(1, 0, "Tues");
console.log(array);
// [ 'Mon', 'Tues', 'Wed', 'Thurs' ]
```

In the snippet above we inserted, Tuesday into the array. The first argument is the index of the array you want to mutate, the second argument is the number of items we want to remove after the index we specified as the first argument, and the last argument is the value or list of comma-separated values we want to add to the array. However, this function does not even return a value instead it mutates the original array. Now you are wondering how on earth Javascript got away with this for so long. The community realized that things had to be done differently.

```typescript
const array = ["Mon", "Wed", "Thurs"];

const spliced = array.toSpliced(1, 0, "Tues");
console.log(spliced)
// [ 'Mon', 'Tues', 'Wed', 'Thurs' ]'
console.log(array)
// ["Mon", "Wed", "Thurs"];
```

Now we used the `toSpliced` method we have solved the irregularities with the `splice` method. They are identical in the way they work but `toSpliced` will not mess around with the original array. Instead, it will return a spliced copy of the array. But is this not the default behavior?

## Find the Last Item easily

Gone are the days of sweating to find the last occurrence of an item in an array. You see this situation is quite tricky to navigate in Javascript and often requires a strong understanding of arrays. You had to resolve to the ugly spell book to pick a hack for the situation, adding more code than you'd like to maintain in the future. We don't need to do things that way anymore and as such we now have two methods for dealing with situations like this. The first method `findLast` finds the last occurrence of a value in an array while the second method, `findLastIndex` gives us the index of that method.

```typescript
const array = [2, 4, 5, 2, 6, 8, 2, 5];

const lastItem = array.findLast((item) => item % 2 !== 0);

console.log(lastItem)
// 5
```

In the snippet above we use the `findLast` method to find the last odd number in the array. We get back `5` and rightfully so, this method works very much like the `find` method on an array just `findLast` returns the last item while `find` returns the first item.

```typescript
const array = [2, 3, 5, 2, 6, 7, 2, 5];

const lastItem = array.findLastIndex((item) => item % 2 !== 0);

console.log(lastItem);
// 7
```

In the snippet above we use the `findLastIndex` method to get the index of the last occurrence of the item. This method is similar to the `findIndex` method which returns the index of the first item that passes a predicate.

## No more index mutations

We don't have to run indexed mutations on arrays anymore. When I say indexed mutation I'm talking about using the index of an array together with the square bracket notation to update a value in an array. All these mutations are side-effects and they prevent our code from being pure functions and pure functions are the bedrock of functional programming. There is a new method, `array.with` that allows us to create a copy of any array while updating/removing items at a particular index.

```typescript
const colors = ["red", "green", "blue"];
const updatedColors = colors.with(1, "yellow"); // ["red", "yellow", "blue"]
console.log(colors); // ["red", "green", "blue"]
```

This method returns an immutable copy of an array with the specified element replaced. This method will not mutate the original array instead it will create a copy of the original array and replace the specified element only in the new array.

Hope you found this useful, are there other new Javascript array methods you know that I left out of this post? I'd be glad if you can share them with us. What are your thoughts on the post? Let me know using the comment section. If you are looking at learning React then you can check out my [YouTube channel](https://youtube.com/@netcreed?si=yf63gXAtyUbHGFt9) where [I have a course on React for Javascript developers](https://youtube.com/playlist?list=PLQOQaFJExIyOjLpBBSJAgGnLYUL3yjAUr&si=qTKqjmifaqohXFnd) with over 13 videos on getting started with building UIs with React, and another [7 part series on React Hooks](https://www.youtube.com/playlist?list=PLQOQaFJExIyMzXZTyA23G344KZ_REk1Ry), well what are you waiting for? Check it out.