Remove item from an array in JavaScript where order doesn't matter

This is an optimization. You should avoid optimizations if there is no need.

If you want to remove an item from an array and mutate the array, you could use splice like shown below.

const array = ['a', 'b', 'c'];
let index = 1;
array.splice(index, 1); // Slow
console.log(array); // ["a", "c"]

But if the order of the array doesn't matter, you can:

  1. Copy the last item to the position you want to remove
  2. Remove the last element just copied
const array = ['a', 'b', 'c'];
let index = 1;
array[index] = array[array.length - 1];
array.pop(); // Orders of magnitude faster!
console.log(array);

You might be tempted to do array[i] = array.pop(). But this fails if you are trying to move the last item of the arrray.

// Don't do this:
const array = ['a', 'b', 'c'];
let index = 2; // 2 is the last position of the array
array[index] = array.pop();
console.log(array);

source

Questions

What's the output?

const arr = [1, 2, 3];
arr[0] = arr[arr.length - 1];
arr.pop();
console.log(arr);

What's the output?

const arr = [1, 2, 3];
arr[2] = arr.pop();
console.log(arr);