Use splice() instead of delete for arrays in JS


var words = ["Hello", "World", "and", "some", "random", "text"]
console.log(words.length); // returns 6

delete words[2]
console.log(words.length); // returns 6


Delete replaces the item with "undefined" instead of the removing it from the array

The correct approach to remove an item from an array is to use "splice", The splice() method adds/removes items to/from an array, and returns the removed item(s)

Syntax
array.splice(index, howmany, item1, ....., itemX)


var words = ["Hello", "World", "and", "some", "random", "text"]
console.log(words.length); // returns 6

words.splice(2, 1)
console.log(words.length); // returns 5

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers