Array in javascript

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

Create an array

var numArray = ["one", "two"];
console.log(numArray.length); // 2

Access an array

var firstVal = numArray[0];
console.log(firstVal); // one

Loop over an array using forEach

numArray.forEach(function(item, index, array){
console.log(item, index);
one 0
two 1

Add new value in array using push

console.log(numArray); // ["one", "two", "three"]

Remove from the end of an array using pop

console.log(numArray); // ["one", "two"]

Remove from the front of an array using shift

console.log(numArray); // ["two"]

Add to the front of an array using unshift

console.log(numArray); // ["one", "two"]

Find the index of an item in the array using indexOf

var pos = numArray.indexOf("two");
console.log(pos); // 1

Remove an item by index position using splice

numArray.splice(pos, 1); //here pos contains index of array element.
console.log(numArray); //["one", "three"]

Copy an array using slice</em

var noArray = numArray.slice();
console.log(noArray); // ["one", "three"]

Two dimensional array

var mulArray = [['a'],['b']];
console.log(mulArray); // [["a"], ["b"]]

Create a multidimensional Object array

var stepsIn = {
0:{x:-30, y:60, rotation:180, transformOrigin:"90% 80%"},
1:{x:-20, y:80, rotation:180,},
console.log(stepsIn); // this array contains elements as a object

Find out multidimensional object array’s length

function countInObject(obj) {
var count = 0;
// iterate over properties, increment if a non-prototype property
for(var key in obj) if(obj.hasOwnProperty(key)) count++;
return count;
console.log(countInObject(stepsIn)); //2



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s