Register to get access to free programming courses with interactive exercises

Deleting array elements JS: Arrays

In JavaScript, there is no easy way to remove an element from an array. The delete instruction is intuitive, but it only clears the value, and the cell itself doesn't go anywhere:

const numbers = [1, 10];
delete numbers[0];
console.log(numbers);
// => [ <1 empty item>, 10 ]

And the splice method requires the element to be accessed in a more complex way than would otherwise be intuitive.

At the same time, the need to remove arises regularly. And usually not a single item is deleted, but a set of items according to certain rules. For example, the compact operation, which removes null values from an array, is quite common. How do you implement it properly?

In the vast majority of situations, changing an array should translate into creating a new array with no elements to delete. Below is an example of the compact() function being implemented.

const compact = (coll) => {
  // Initializing the result
  // If an input collection is empty, then the result will be an empty array
  const result = [];

  for (const item of coll) {
    if (item !== null) {
      result.push(item);
    }
  }

  return result;
};

console.log(compact([0, 1, false, null, true, 'wow', null]));
// => [ 0, 1, false, true, 'wow' ]
console.log(compact([]));
// => []

The main thing to pay attention to is that there are no modifications to the original coll array. Instead, a new array, result, is created, which is filled only with values that meet the condition. This is how you should understand the phrase “remove something from an array”. Code using a new array is less error-prone, easier to debug, and leaves more room for analysis. You can always look at the original array if something went wrong. You can always observe the process of filling the resulting array, which allows you to clearly see if the conditions set are correct.

In fact, the code above is an example of aggregation. Only unlike the previous examples, where the result was a primitive type, here the result is an array. This is perfectly normal. As you will see later, the result can also be a more complex structure. The array thinning operation (removing elements according to certain conditions) itself is usually called filtering.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY