Monday, August 12, 2013

Javascript shift(), unshift(), pop(), push(), concat(), splice() functions

Hi to day i'll digg into shift(), unshift(), pop(), push(), concat(), splice() functions of javascript :


var arr, alphaNumeric;

var alpha = ['A', 'B', 'C'];
var numeric = [10, 20, 30];
arr = alpha;
console.log('ORIGINAL ARRAY: '+ arr);

// SHIFT
var shifted = arr.shift();
console.log('SHIFTED: '+ shifted);
console.log('ARRAY AFTER SHIFT: '+ arr);

// UNSHIFT
var toUnshift = ['D'];
arr.unshift(toUnshift);
console.log('UNSHIFTED: '+ toUnshift);
console.log('ARRAY AFTER UNSHIFT: '+ arr);

// POP
var popped = arr.pop();
console.log('POPPED: '+ popped);
console.log('ARRAY AFTER POP: '+ arr);

// PUSH
var toPush = ['Z'];
arr.push(toPush);
console.log('PUSHED: '+ toPush);
console.log('ARRAY AFTER PUSH: '+ arr);

// CONCATE
alphaNumeric = alpha.concat(numeric);
console.log('ARRAY: '+ arr);
console.log('ALPHA: '+ alpha);
console.log('NUMERIC: '+ numeric);
console.log('ALPHANUMERIC: '+ alphaNumeric);
alphaNumeric = alpha.concat(1, [2, 3]);
console.log('NEW ALPHANUMERIC: '+ alphaNumeric);

// SPLICE
var startingIndex = 2, howManyToRemove = 2;
var elementsToAdd = ['P'];
var removed;
var minVal = Number.MIN_VALUE, maxVal = Number.MAX_VALUE;

//removed = alphaNumeric.splice(); // does nothing
//removed = alphaNumeric.splice(startingIndex); // removes all from the given index
//removed = alphaNumeric.splice(startingIndex, howManyToRemove); // removes 'n' from the given index
removed = alphaNumeric.splice(startingIndex, howManyToRemove, elementsToAdd); // removes 'n' from the given index, and then add new elements
//removed = alphaNumeric.splice(startingIndex, minVal);
//removed = alphaNumeric.splice(startingIndex, maxVal);

//console.log('minVal: '+ minVal);
//console.log('maxVal: '+ maxVal);

console.log('SPLICED: '+ removed);

console.log('ARRAY AFTER SPLICE: '+ alphaNumeric);