JS: Arrays
Theory: Deleting array elements
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:
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.
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.
Recommended programs
Completed
0 / 22

