1

I have ran the simple javascript code. where i want to delete an element from the array. it is not being completely deleted although it remains undefined after deleting the element itself. it should not leave any gap in the array.

var arr = ['dog',34,36.33,'apple',,,];
alert(arr);
delete arr[2];
alert(arr);

i have check the syntax of delete is correct. Am i doing wrong. if it is so, please find the soln. i want complete array free from deleted elements.

2
  • delete does delete properties, not splice items out of an array. Commented Aug 11, 2014 at 16:32
  • here delete is operator. var arr = [2,34,36.33,'apple']; arr.slice(2,1); alert(arr); here it does not give the arr free from arr[2] Commented Aug 11, 2014 at 16:35

1 Answer 1

2

Use .splice() instead:

var arr = ['dog',34,36.33,'apple'];
console.log(arr); // ["dog", 34, 36.33, "apple"] 
arr.splice(2,1);
console.log(arr)  // ["dog", 34, "apple"] 
Sign up to request clarification or add additional context in comments.

1 Comment

splice() not slice()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.