From the end of array an element can be removed by setting the length property to value that is less than present value. An element with index greater than or equal to new length will be removed.
var ar = [1, 2, 3, 4, 5, 6]; ar.length = 4; // set length to remove elements console.log( ar ); // [1, 2, 3, 4]
Array element can be removed with delete operator. Delete operator neither effects the length property nor the indexes of subsequent elements.
var ar = [1, 2, 3, 4, 5, 6]; delete ar; // delete element with index 4 console.log( ar ); // [1, 2, 3, 4, undefined, 6] alert( ar ); // 1,2,3,4,,6
Removal of Elements at the End of Array Pop method is used for removing last element from an array. It also returns that element and updates length property. Method pop will modify the array on which it is invoked.
var ar = [1, 2, 3, 4, 5, 6]; ar.pop(); // returns 6 console.log( ar ); // [1, 2, 3, 4, 5]\
Removal of Elements at the Beginning of Array Shift method is used for this purpose and it works quite similar to pop method except it removes the first element from the array instead of last element. This method will return the element that is removed and updates the remaining element indexes as well as updates length property. It also modifies array over which it is invoked.
var ar = [‘zero’, ‘one’, ‘two’, ‘three’]; ar.shift(); // returns “zero” console.log( ar ); // [“one”, “two”, “three”]
Removal of Elements from the Middle of Array For this purpose splice method is used. Here the initial argument specifies location where to begin element addition and removal. The second argument will specify the quantity of element to be removed. Third and other subsequent arguments are simply optional which specify elements to be added to the array. Below we are using splice method for removal of two elements from third position.
var ar = [1, 2, 3, ‘a’, ‘b’, ‘c’]; // arguments: start position, number of elements to delete console.log( ar.splice(3, 2) ); // [“a”, “b”] console.log( ar ); // [1, 2, 3, “c”]
A user oriented solution on cutting edge technology to engage customers or boost your brand to eventually edge out your competitor you require customized mobile application, web application or an e-commerce solution. Websri boast best fit developers, designers that were key to partner with multiple Fortune 500 firms to deliver industry oriented web,mobile and e-commerce solution always.