Array, Most Challenging and Adorable Topic in Programming

Open Source 23 Mar , 2013  

Buffer

urdlIn my Previous Post I’ve described Objects in just simple 5 steps, but This my friends is the most easy, challenging and adorable topic is… Array may help you in various situations when you don’t have anything but The Array !

Now Question arises that what Arrays are Actually???, So let me tell you that array are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays too …

HOW TO CREATE ARRAY :

We can create array in two ways, To create an array, either use the object constructor or the literal declaration, by assigning the variable a list of values after the declaration. Lets see it using an example where The literal declaration is generally preferred.

// A simple array with constructor.
var array_example_1 = new Array( "hello", "world" );
// Literal declaration, the preferred way.
var array_example_2 = [ "hello", "world" ];

If the values are unknown, it is also possible to declare an empty array, and add elements either through functions or through accessing by index:

// Creating empty arrays and adding values
var array_example = [];

// adds "hello" on index 0
array_example.push( "5" ); // adds "world" on index 1
array_example.push( "7" ); // adds "!" on index 2
array_example[ 2 ] = "2";
array_example[ 3 ] = "12";
array_example[ ]

So in the Above example .push() is a function that adds an element on the end of the array and expands the array respectively, and if you don’t know the length of array so using .push its better. You also can directly add items by index like array_example[0] = ‘x’; array_example[1] = ‘y’;

Accessing array elements

single-dimensional-array

//Accessing Array Items by index

console.log( array_example[0] ); //prints "5"
console.log( array_example[1] ); //Prints "7" );
console.log( array_example[2] ); //Prints "2"

Types of Array

Array

Array Properties:

1. constructor:  Constructor specifies the function that creates an object’s prototype.

2. length : This is the function which reflects the number of elements in an array.

// Length of an array
var array_example= [ "hello", "world", "!" ];
console.log(array_example.length ); // 3

Array Methods:

Mutator methods

These methods modify the array:

pop

Removes the last element from an array and returns that element.

push

Adds one or more elements to the end of an array and returns the new length of the array.

// pushing and popping
var array_example = [];

array_example.push( 0 ); // [ 0 ]
array_example.push( 2 ); // [ 0 , 2 ]
array_example.push( 7 ); // [ 0 , 2 , 7 ]
array_example.pop();     // [ 0 , 2 ]

reverse

Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.

// reverse
var array_example = [ "world" , "hello" ];

// [ "hello", "world" ]
array_example.reverse();

shift

Removes the first element from an array and returns that element.

// queue with shift() and push()
var array_example = [];

array_example.push( 0 ); // [ 0 ]
array_example.push( 2 ); // [ 0 , 2 ]
array_example.push( 7 ); // [ 0 , 2 , 7 ]
array_example.shift();   // [ 2 , 7 ]

sort

Sorts the elements of an array.

// sorting without comparing function
var array_example = [ 3, 4, 6, 1 ];

array_example.sort(); // 1, 3, 4, 6

splice

Removes a certain amount of elements and adds new ones at the given index. It takes at least three parameters:

array_example.splice( index, length, values, … );

Index – The starting index.

Length – The number of elements to remove.

Values – The values to be inserted at the Index position.

// splice example
var array_example = [ 0, 7, 8, 5 ];
array_example.splice( 1, 2, 1, 2, 3, 4 );

console.log( array_example ); // [ 0, 1, 2, 3, 4, 5 ]

unshift

Adds one or more elements to the front of an array and returns the new length of the array.

// unshift
var array_example = [];

array_example.unshift( 0 ); // [ 0 ]
array_example.unshift( 2 ); // [ 2 , 0 ]
array_example.unshift( 7 ); // [ 7 , 2 , 0 ]

Accessor methods

These methods do not modify the array and return some representation of the array.

concat

Returns a new array comprised of this array joined with other array(s) and/or value(s).

// Concatenating Arrays
var array_example = [ 2, 3, 4 ];
var myOtherArray = [ 5, 6, 7 ];

// [ 2, 3, 4, 5, 6, 7 ]
var wholeArray = array_example.concat( myOtherArray );

join

Joins all elements of an array into a string.

/ Joining elements
var array_example = [ "hello", "world", "!" ];

// The default separator is a comma
console.log( array_example.join() );     // "hello,world,!"

// Any string can be used as separator...
console.log( array_example.join(" ") );  // "hello world !";
console.log( array_example.join("!!") ); // "hello!!world!!!";

// ...including an empty one
console.log( array_example.join("") );   // "helloworld!"

slice

Extracts a section of an array and returns a new array.

// slicing
var array_example = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
var newArray = array_example.slice( 3 );

console.log( array_example );  // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
console.log( newArray ); // [ 4, 5, 6, 7, 8 ]

toSource [Non-standard]

Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the Object.prototype.toSource method.

<script>

function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}

var person=new employee("Ankita Gupta","Software Engineer",1988);

document.write(person.toSource());
// Result will be ({name:"Ankita Tupta", jobtitle:"Software Engineer", born:1988})
</script>

toString

Returns a string representing the array and its elements. Overrides the Object.prototype.toString method.

var num = 15;
var n = num.toString();
//Result will be 15

indexOf

Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
//Output will be 13

lastIndexOf

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

var str="Hello planet earth, you are a great planet.";
var n=str.lastIndexOf("planet");
//output will be 36

Iteration methods

forEach

Calls a function for each element in the array.

/ native forEach
function printElement( elem ) {
    console.log( elem );
}

function printElementAndIndex( elem, index ) {
    console.log( "Index " + index + ": " + elem );
}

function negateElement( elem, index, array ) {
    array[ index ] = -elem;
}

array_example = [ 1, 2, 3, 4, 5 ];

// prints all elements to the console
array_example.forEach( printElement );

// prints "Index 0: 1" "Index 1: 2" "Index 2: 3" ...
array_example.forEach( printElementAndIndex );

// array_example is now [ -1, -2, -3, -4, -5 ]
array_example.forEach( negateElement );

 

Some Other Functions :

every

Returns true if every element in this array satisfies the provided testing function.

some

Returns true if at least one element in this array satisfies the provided testing function.

filter

Creates a new array with all of the elements of this array for which the provided filtering function returns true.

map

Creates a new array with the results of calling a provided function on every element in this array.

reduce

Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

reduceRight

Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

Thats all, This is enough for to know about Array, I know its little much but all these functions are very tricky in situations, where you need something which help to shorten your code… you will feel lucky sometimes that you have these functions available 🙂

, , , , ,