Array functions in JavaScript
Here are some of the functions useful for array operations
Push() - Appends one or more elements to the end of an array
Pop() - Pops out (removes) one element from the end of an array
Unshift() - Adds one or more elements to the beginning of an array
Shift() - Removes one element from the beginning of an array
Splice() - Removes elements specified number of items from the starting index and also optionally allows insertion of items on the start index.
Thanks to Ben Nadel for sharing this useful piece of information.
Push() - Appends one or more elements to the end of an array
var data = [ "A" ];
data.push( "B" );
data.push( "C" );
data.push( "B" );
data.push( "C" );
Result
data = ["A","B","C"]
data = ["A","B","C"]
Pop() - Pops out (removes) one element from the end of an array
var data = ["A","B","C"];
data.pop();
data.pop();
Result
data = ["A","B"];
data = ["A","B"];
Unshift() - Adds one or more elements to the beginning of an array
var data = [ "A" ];
data.unshift( "B","X" );
data.unshift( "C" );
data.unshift( "B","X" );
data.unshift( "C" );
Result
data = ["C","B","X","A"]
data = ["C","B","X","A"]
Shift() - Removes one element from the beginning of an array
var data = ["A","B","C"];
data.shift();
data.shift();
Result
data = ["B","C"];
data = ["B","C"];
Splice() - Removes elements specified number of items from the starting index and also optionally allows insertion of items on the start index.
// array.splice(start Position,number of elements,[elements to be inserted])
var data = ["A","B","C","D"];
console.log(data.splice(1,2,"x","y"));
console.log(data);
var data = ["A","B","C","D"];
console.log(data.splice(1,2,"x","y"));
console.log(data);
Result
["B", "C"]
["A", "x", "y", "D"]
["B", "C"]
["A", "x", "y", "D"]
Thanks to Ben Nadel for sharing this useful piece of information.
Comments