Javascript remove last element from array immutable

Remove Element From Array In An Immutable Way With Code Examples

With this piece, we’ll take a look at a few different examples of Remove Element From Array In An Immutable Way issues in the computer language.

const arr = ['a', 'b', 'c', 'd', 'e'];

const indexToRemove = 2; // the 'c'

const result = [...arr.slice(0, indexToRemove), ...arr.slice(indexToRemove + 1)];

console.log(result);
// ['a', 'b', 'd', 'e']

Numerous real-world examples illustrate how to deal with the Remove Element From Array In An Immutable Way issue.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.13-Jun-2022

Is array slice immutable?

You can create an immutable copy of an array using Array. slice() with no arguments, or with the Array.24-Feb-2021

No, you cannot make the elements of an array immutable. But the unmodifiableList() method of the java. util. Collections class accepts an object of the List interface (object of implementing its class) and returns an unmodifiable form of the given object.15-Oct-2019

How can we make immutable array?

There is one way to make an immutable array in Java: final String[] IMMUTABLE = new String[0]; Arrays with 0 elements (obviously) cannot be mutated. This can actually come in handy if you are using the List.

How do I remove something from an array in Java?

Approach:

  • Get the array and the index.
  • Form an ArrayList with the array elements.
  • Remove the specified index element using remove() method.
  • Form a new array of the ArrayList using mapToInt() and toArray() methods.
  • Return the formed array.

How do you remove an element from an array based on value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.06-Nov-2015

What is an immutable array?

An immutable array or object is a unique copy of the original that, when manipulated, does not affect the original.10-Jun-2019

Is array push immutable?

Immutable array operations. Array has several mutable operations – push, pop, splice, shift, unshift, reverse and sort. Using them is usually causing side effects and bugs that are hard to track. That’s why it’s important to use an immutable way.23-Jul-2019

What is mutable vs immutable?

A mutable object can be changed after it’s created, and an immutable object can’t. That said, if you’re defining your own class, you can make its objects immutable by making all fields final and private.

Why are arrays immutable in Java?

A Mutable object means the object state or values can be changed, while an immutable object means the object values are fixed. Arrays in Java are mutable because you can still change the values of the array after it has been created.21-Feb-2022

Performance testing a for loop vs. .indexOf and splice vs. .filter

I demonstrate how to use .indexOf and .splice to remove an item from an array. Then I compare performance with a for loop and the .filter method.

Photo by Jackson Simmer on Unsplash

A common question in JavaScript is what’s the fastest way to remove a value from an array using built-in Javascript methods (vanilla JS).

In other words, the fastest way to modify the array to no longer include a specific value.

This article tests the performance of 4 different methods for removing a specific item from an array in JavaScript.

Removing an item from an Array

One way to solve this problem is using Array.prototype.indexOf() to find the index of the value, then Array.prototype.splice() to remove that item:

Note that .indexOf returns -1 if the index is not found, but .splice interprets an index of -1 as the last item in the array, just like .slice.

The following code using the ? question mark operator is equivalent:

You could also write a one-liner if you really don’t mind the performance hit of searching the entire array twice if the value is found:

All of these methods only remove the first instance of the given value:

I’ll discuss options for removing all matching items later in this article.

What about a for loop?

A perfectly good option to remove an item from an array would be to use a for loop, though it could potentially be harder to read in your code:

To make it equivalent to using .indexOf and only remove the first instance, I used a variable to keep track of whether the value had been removed.

The following would remove all instances using .indexOf and .splice:

And the following would remove all instances using a for loop:

Which is faster?

Performance testing using these jsPerf test cases shows a big difference between the two methods of removing an item from an array:

Javascript remove last element from array immutable

Using a for loop appears 2.5x faster than .indexOf and .splice.

This difference is magnified when removing all instances of the matching value, which I tested in these jsPerf test cases:

Javascript remove last element from array immutable

As you can see, the for loop appears 5x faster compared to the while loop using .indexOf and .splice in a really inefficient manner.

But these results are misleading — because the processor is still crunching 4000 operations each millisecond (4,000,000 ops/sec).

As you will see later, .indexOf and .splice actually have better performance than the for loop when dealing with large arrays of 10,000 items.

What about .filter?

It is a fair point to mention the built-in Array.prototype.filter() method, one of JavaScript’s functional programming tools.

Here is an example of removing all items from an array using .filter, which returns a filtered array of the values that match the given conditional:

On the plus side, filter results in much less code. But how fast is it?

In these jsPerf test cases, I compared .filter to the super-slow while loop using .indexOf and .splice and the super-fast for loop:

Javascript remove last element from array immutable

As you can see, .filter() is a good choice — a for loop is a bit faster, but .filter() is fine for removing all matching values from an array.

Which is fastest in a big array?

Of course, the above data examines tiny arrays — and my browser is crushing 4 million while loops per second. Plenty of speed.

What if we are working with a bigger array, of say 10,000 items? In that case, performance depends a lot on the data you’re working with.

In a 10,000 item array where the target (the number 5,000) is only found one time, the while loop with .indexOf and .splice actually wins out:

Javascript remove last element from array immutable

For this use case, .filter is a big loser, as a for loop is about 5x faster. But .indexOf and .splice are more than twice as fast as the for loop.

Compare that to a 10,000 item array where the target (the number 5,000) is found as every other item in the array. The results are the exact same:

Javascript remove last element from array immutable

Thinking about what those numbers mean, .filter is only taking 0.25 milliseconds to process the array of 10,000 items — still quite fast.

The take-home message is don’t engage in premature optimization.

Use the most readable code you can, then optimize only if necessary.

How to avoid mutation?

Note that Array.prototype.splice() modifies the array in place, which is generally good for performance, but you can get side effects (bugs).

Be aware that modifying an object, also called mutating it, is sometimes considered bad code practice, because of the possibility of side effects.

There is even an ESLint plugin (eslint-plugin-immutable) that disables all object mutation completely — a good idea for preventing bugs.

But how would you remove an item from an array without mutating the original array? You just need to make a shallow copy of the array:

The for loop method already avoids mutation, because you are .pushing items to a new array. This is inherently a shallow copy of the array.

If you need to make a deep copy, due to nested objects or arrays inside of an array, then check out my article on deep copying arrays in JavaScript:

Conclusion

Now you understand how to combine .indexOf and .splice to remove an entry from a JavaScript array, thus mutating the array in place.

To avoid mutating the array, make a shallow copy or use a for loop.

A for loop is also a great choice if you need to remove every matching value from an array— or just use .filter to filter out the matching items.

While combining .indexOf and .splice is slower than using a for loop for small arrays, the performance varies for bigger arrays.

My recommendation is to use the most readable versions in your code:

  • .indexOf and .splice to remove just the first instance of a value
  • .filter to remove every instance of a value from an array

Those methods are going to be inherently more self-documenting than a for loop, where you will need to write a comment explaining your code.

For the best performance when removing items from large arrays, consider .indexOf and .splice, as that method can be quite fast.

Happy coding! 😄🥴😂

Photo by Anne Nygård on Unsplash

Join my email list to get free access to all of my Medium articles.

How do you delete the last element of an array in JavaScript?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.

What method can remove the last element of an array?

The pop() method removes the last element from an array and returns that element.

How do you remove an element from an array without mutating?

How to remove an element from an array without mutating the array.
prototype. slice().
prototype. slice() together with Array. prototype. concat().
prototype. filter().
A for loop and Array. prototype. push().

How do you insert and remove the last element of an array?

The array_pop() function, which is used to remove the last element from an array, returns the removed element.