Using javascript array function splice to modify array contents

Javascript array object has lots of pre-defined functions that makes life easy. Among them, splice is the method lot of developers are not aware of.

Using splice, you can remove an element in array, replace array contents without copying, iterating through entire elements. Prototype uses existence of splice method to identify whether an object is an array or not (Object.isArray). so, no need to worry about browser compatibilities.

I used to iterate through entire array object to remove an element like the following

var arrObj = ['1', '4', '3', '2'];
var anotherArray = [];
for (var i = 0;i <=arrObj.length; i++) {
if(arrObj[i] != '3') {
anotherArray.push(arrObj[i]);
}
}

We need to iterate through entire array to remove an element if above method is followed.
Using splice method,


var arrObj = ['1', '4', '3', '2'];
for(var i = 0;i <=arrObj.length; i++) {
if(arrObj[i] == '3') {
arrObj.splice(i,1);
break;
}
}
If you print arrObj contents after performing above operation, it will result in ['1','4','2']. You can stop iterating as soon as the required object is found, no overhead of creating new array.


Attached is the source code is used to profile the performance of remove method suggested by John Resig with the native splice method. You need to have Firefox with Firebug installed to load this page and see the results.


Enable firebug and refresh the p
age to see profile results.

Attached is the screenshot showing the profiler output,
testfunc is a wrapper over native splice method as firebug is not giving profile info of native javascript methods.

Results show splice method is three times faster than remove method. Can play with different array lengths.


Comments

Prashant said…
John Resig, the jQuery authors suggests this approach to removing elements from array.
amar said…
I think we need to run performance tests on both the methods. splice can also be used to replace array contents.
navya said…
Wow. This really made my day. Thanks a lot!

JavaScript Training in CHennai JavaScript Training in CHennai JQuery Online Training JQuery Online Training
HTML5 CSS3 JavaScript Training in Chennai | HTML5 Online Training
navya said…
Wow. This really made my day. Thanks a lot!

JavaScript Training in CHennai HTML5 Training in Chennai HTML5 Training in Chennai JQuery Training in Chennai JQuery Training in Chennai JavaScript Training in Chennai JavaScript Training in Chennai

navya said…
Wow. This really made my day. Thanks a lot!

JavaScript Training in CHennai JavaScript Training in CHennai JQuery Online Training JQuery Online Training
HTML5 CSS3 JavaScript Training in Chennai | HTML5 Online Training

Popular posts from this blog

Proper way to have an anchor tag with onclick event

Some thoughts on MongoDB Nodejs driver

CORS issues with IE9 and workarounds