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.
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 page 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.
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 page 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
JavaScript Training in CHennai JavaScript Training in CHennai JQuery Online Training JQuery Online Training
HTML5 CSS3 JavaScript Training in Chennai | HTML5 Online Training
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
JavaScript Training in CHennai JavaScript Training in CHennai JQuery Online Training JQuery Online Training
HTML5 CSS3 JavaScript Training in Chennai | HTML5 Online Training