Thursday 20 December 2018

JavaScript: How to delete an element of array

Using delete operator, you can delete the element of array.

Syntax
delete array[index]

HelloWorld.js
function print_array_info(arr){
  console.log("arr length is : " + arr.length);
  console.log(arr);
}

var arr = [2, 3, 5, 7, 11];

print_array_info(arr);

console.log("Deleting element at index 2");
delete arr[2];

print_array_info(arr);

Output
arr length is : 5
Array(5) [ 2, 3, 5, 7, 11 ]
Deleting element at index 2
arr length is : 5
Array(5) [ 2, 3, <1 empty slot>, 7, 11 ]

As you see the output, even though I deleted the element at index 2, there is no change in array length. delete operator just remove the element from the array, but do not alter the length.

In the following example, arr[2] is removed with delete. However, arr[2] is still addressable and returns undefined. If you want to delete an element and make sure that array length is also affected as per this, use splice method.


HelloWorld.js
var arr = [2, 3, 5, 7, 11];

console.log("Value at arr[2] is : " + arr[2]);
console.log("Deleting element at index 2");

delete arr[2];

console.log("Value at arr[2] is : " + arr[2]);

if(2 in arr){
  console.log("Property 2 is exist in array");
}else{
  console.log("Property 2 is not exist in array");  
}

Output
Value at arr[2] is : 5
Deleting element at index 2
Value at arr[2] is : undefined
Property 2 is not exist in array

Use splice method to delete the elements in better way, it do not create empty slots.



Previous                                                 Next                                                 Home

No comments:

Post a Comment