Removing elements from an array in javascript

Sep 27, 2011 No Comments by Mahdi Pedram

If you are trying to remove elements from an array. and do not care what those elements are, you shouldn't use array slice, array splice.
however there is an easier way of doing this.

by just changin the length of an array we can modify our array and remove items from it.

 
var arr = [1,2,3,4,5];
arr.length = 2;
console.log( arr ); //[1,2]; // we removed 3 items from our array.
 

let's now wrap it in a function
as you can see arrays are objects and objects are passed by reference.

 
function popItems(arr, length){
 return arr.length -= length;
}
var arr = [1,2,3,4,5];
popItems(arr, 2);
console.log(arr ); // [1,2,3]
 

it is recommended to have all your functionalists encapsulated into objects so programmers could use them over and over.
so performance and speed are vital. I personally will use arr.length.

now one would say I still prefer to use array slice or spice or even using it for loop.

Array Slice Version

 
 
function popItems(arr, length){
 return arr.slice(0,-length);
}
var arr = [1,2,3,4,5];
arr = popItems(arr, 2);
console.log(arr ); // [1,2,3]
 

Array Splice Version

 
 
function popItems(arr, length){
 return arr.splice(0,arr.length-length);
}
var arr = [1,2,3,4,5];
arr = popItems(arr, 2);
console.log(arr ); // [1,2,3]
 

For Loop Version

 
 
function popItems(arr, length){
  for( var i =0; i<length; i++){ arr.pop(); }
  return arr;
}
var arr = [1,2,3,4,5];
arr = popItems(arr, 2);
console.log(arr ); // [1,2,3]
 
javascript

About the author

I'm Web Developer , I spent most of my time on programming web applications ,I'm both Front-end , Back-end Developer . Coding is part of my life , I don't do programming for life , I am alive to Code
No Responses to “Removing elements from an array in javascript”

Leave a Reply