Arrays

Arrays are use to store ordered collections of data. If we have multiple items, then we can use arrays to store these values. Array prototype methods are used to perform mutation operations in JavaScript. There is no fixed length of an array. An array can contain multiple value types and the number of items can be mutated at any point after initialization.

Array types

There are two array types in JavaScript:

  • Nominal type: This type of array has a unique identity.
  • Structure type: This array type looks like an interface; it is also known as duck type. It uses a specific implementation of a behavior.

Note

Sparse array

In programming languages, a sparse array denotes an array that has the same values such as 0 or null. There is a large number of zeroes in an array storage, which occurs in a sparse array. In a sparse array, indexes do not start from 0. In a sparse array, lengths of the elements are less than the length of the property.

In JavaScript, the length property is not the actual amount of elements in the array, it is last index+1. So, in case of a sparse array, this is crucial to deal with the blank indexes. Consider the following example:

var person=[];
Person[1]="Ali";
Person[20]="Ahmed";
Alert(person.length);// it will be 21 length

Array type object

Some objects in JavaScript look like an array, but in reality, they are not arrays. They are known as array-like objects.

An array-like object:

  • Has: This tells you the number of elements an object has
  • Does not have: These are array methods such as indexOf, push, and forEach

Note

Strings as an array

There are some strings in JavaScript that behave like an array. If we make a string like an array, then it will only be treated as an array. There are some methods in arrays such as push(), reverse(), and so on, which do not work on strings.

Creating arrays

In JavaScript, there are two ways to create arrays:

  • Using an array initializer
  • Using an array constructor

You can use either of these two methods.

We have a comma-separated string in brackets in an array initializer; for example:

var students= ["Ali","Ahmed","Amina"];

In JavaScript, you can also create an array using an array constructor using a new keyword, which creates an array and assigns values to it; for example:

var students=new Array ("Ali,"Ahmed","Amina");

Tip

The array initializer method is a quick and good way of initializing an array because its execution speed is higher than that of the constructor method. If you do not pass any argument in an array constructor, then it will set its length to zero.

Array initializer

Arrays are used to store ordered collections of data in a single variable. It means that when you want to store a list of items then you should use an array. Before using an array in your program you need to first initialize it.

In an array initializer, there are comma separated lists of items stored in a variable, for example:

var a1=[];
var a2=[2];
var a3=[1,2,3];
var a4=['hi', [2]];

Tip

When you initialize an array using an array initializer, the type does not have to be the same for all items. Also, arrays can have zero length.

Array constructor

There are three different ways in which you can use an array constructor. Their syntax is as follows:

var a1=new array(); // new empty array
var a2=new array(2); // new array of size 2
var a3= new array(1,2,3); // new array containing 1, 2, 3

If you call an array constructor without argument it will set its length to zero.

If an array constructor has only one argument then this argument will initialize its new length.

If you call an array with two or more elements, the the argument will initialize an array with size equal to the number of parameters.

Reading and writing array elements

To read and write elements from an array we use square brackets []. It works as accessing object properties. Inside the brackets there should be a non-negative number. The syntax for both reading and writing in an array is the same. Values are also indexed in an array. You read values index by index. The array's reference should be on left side of bracket.

Consider the following example:

var obj=["abc"];
var start=obj[0]; //its is for reading

Document.Write(start);

var obj[1]="hello";
i="world";
Obj[i]="hello world";//writing
Document.Write(obj[i]);

The output of this would be as follows:

Hello world

Multidimensional arrays in JavaScript

Like other programming languages, you can also create multidimensional arrays in JavaScript. Their syntax is same as in other languages. In multidimensional arrays you create arrays within arrays of nested array loops.

You can create an array by adding more arrays for each dimension you need. Creating a multidimensional array is useful when you need to cover the whole storage with information. If most of your data is sparse, meaning if array is empty, then a better technique to store the information is using an associative array. Here is an example of creating a multidimensional array in JavaScript:

var a=5;
var b=2;
var c=new array();
For(i=0;i<5;i++) {
  C[i]=new array();
  for For(j=0;j<5;j++)
  c[i][j];  }}
}

Properties in an array

An array has a prototype, length, and a constructor as its properties.

Length

In JavaScript, the array length property returns the number of elements in an array.

Returns

This returns an integer value of 32 bit.

Description

We can also use an array length property when we want to empty an array at any time. When you increase the length of any array, it will not increase the number of elements in it. We can set or return the length of any array using the array length property.

Consider the following example:

var num=new Array[1,2,3];
Document. write (num.length);

The output will be as follows:

3

Constructor

An array contractor is used to initialize an array. An array can contain zero or more elements and has the following syntax where array elements are separated by a comma inside square brackets.

var fruits = ["Apple", "Banana"];

Prototype

All array instances inherit from Array.prototype. The prototype constructor of an array allows to add new methods and properties to the Array() object.

Array.prototype is an array itself.
Array.isArray(Array.prototype); // true

You can find detailed information on how to make these changes at MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype).

Array methods

There are several methods that can be performed on arrays to obtain different results. Some of these methods are defined in the following sections.

concat()

The concat() method performs concatenation between two arrays.

Returns

The concat() method returns the concatenated array.

Parameter

The concat() method takes a string to concatenate with.

Description

This takes two arrays and joins them.

var alpha = ['a', 'b', 'c'],
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]

every()

The every() method tests a function for every array element.

Returns

The every() method returns a Boolean true or false.

Parameter

A call back function to be applied on every element of the array.

Description

If every element in an array provides the testing function, then it returns true.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

foreach()

The foreach() method executes a function passed as a parameter for every element of the array.

Returns

The output of each function.

Parameter

A call back function to be called for every element of the array.

Description

The foreach() method calls the functions of each element:

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Note elision, there is no member at 2 so it isn't visited
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

join()

This joins all elements into a string.

Returns

A joined string.

Parameter

Null or a separator to place between array elements.

Description

It joins all elements into a string.

var a = ['One', 'Two', 'Three'];
var var1 = a.join();      // assigns 'One,Two,Three' to var1
var var2 = a.join(', ');  // assigns 'One, Two, Three' to var2
var var3 = a.join(' + '); // assigns 'One + Two + Three' to var3
var var4 = a.join('');    // assigns 'OneTwoThree' to var4

pop()

The pop() method removes the last element of an array, just like a stack.

Returns

The pop() method returns a null parameter.

Parameter

The pop() method takes the null parameter.

Description

It removes the last element of an array, just like a stack.

var myColours = ['Yellow', 'Black', 'Blue', 'Green'];
console.log(myColours); // ['Yellow', 'Black', 'Blue', 'Green']
var popped = myColours.pop();
console.log(myColours); // ['Yellow', 'Black', 'Blue' ] 
console.log(popped); // 'Green'

push()

It adds elements on the last index on an array.

Returns

null.

Parameter

null.

Description

This adds elements at the last index on an array.

var sports = ['cricket', 'baseball'];
var total = sports.push('football');

console.log(sports); // ['cricket', 'baseball', 'football']
console.log(total);  // 3

indexOf()

The indexOf() method returns the first index of an array.

Returns

The indexOf() method returns an index.

Parameter

The indexOf() method takes an array element as a parameter.

Description

It returns the first index of an array.

var array = [2, 5, 9];
array.indexOf(9);     // 2
array.indexOf(7);     // -1 if not found

lastIndexOf()

The lastIndexOf() method returns the last index at which a given element is found inside an array.

Returns

It returns the last index of an array.

Parameter

An array element.

Description

var array = [2, 5, 9, 2];
array.indexOf(2);     // 3
array.indexOf(7);     // -1 if not found

reverse()

The reverse() method reverses the order of all the elements in an array.

Returns

The array.

Parameter

null.

Description

The reverse() method reverses the order of the elements in an array. The first element becomes the last element and so on.

var myArray = ['one', 'two', 'three'];
myArray.reverse(); 

console.log(myArray) // ['three', 'two', 'one']

shift()

In an array, the shift() method removes the very first element and returns that element.

Returns

null.

Parameter

null.

Description

In an array, it removes the very first element and returns the removed element.

var myColours = ['Yellow', 'Black', 'Blue', 'Green'];
console.log(myColours); // ['Yellow', 'Black', 'Blue', 'Green']
var shifted = myColours.shift();
console.log(myColours); // ['Black', 'Blue', 'Green'] 
console.log(shifted); // 'Green'

unshift()

This method adds a new element at the beginning of the array and returns the new array length.

Returns

The new length of the array.

Parameter

The element(s) to add in the array.

Description

This method adds a new element at the beginning of the array and returns the new array length:

var arr = [1, 2, 3];
arr.unshift(0); // arr is [0, 1, 2, 3]

slice()

The slice() method slices an array into a new array.

Returns

The new sliced array.

Parameter

The indices of elements to slice.

Description

This method slices an array into a new array:

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// citrus contains ['Orange','Lemon']

splice()

The splice() method is also used to add new elements to an array by removing existing elements.

Returns

The new spliced array.

Parameter

The indices of elements to remove and the elements to add.

Description

This method is also used to add new elements to an array by removing existing elements:

var myCars = ['Audi', 'BMW', 'Ferrari', 'Volkswagen'];

// removes 0 elements from index 2, and inserts 'Toyota'
var removed = myCars.splice(2, 0, 'Toyota');
// myCars is ['Audi', 'BMW', 'Toyota', 'Volkswagen']
// removed is [], no elements removed

sort()

This sorts an array alphabetically.

Returns

null.

Parameter

null.

Description

Called as an array method, this sorts an array alphabetically (unicode characters) and will not work well with numbers:

var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']

toString()

The toString() method converts the object into a string.

Returns

The toString() method returns a string.

Parameter

The toString() method takes a null parameter.

Description

Converts the array object into a string with its elements separated by commas character.

var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];
var myVar = monthNames.toString(); // 'Jan,Feb,Mar,Apr' to myVar.

ECMA5 Array methods

New array methods were added into the ECMA5 script, which is also known as arrays extras. These are nine new methods. These methods perform common operations working with arrays. These new methods are covered in the following sections.

array.prototype.map()

The map() method creates a new array on the result values from each iteration.

Returns

A modified array.

Parameters

A callback function.

Description

It loops through an array, running a function, and creates a new array based on the return values from each iteration. It takes the same arguments as the forEach() method.

Here is a simple example:

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);

The roots are now as follows:

[1, 2, 3]

array.prototype.filter()

The filter() function creates a new or modified array that consist of values that are processed by the function.

Returns

A modified array.

Parameters

A callback function.

Description

It creates a new array of only those elements that returned true to their callbacks.

Here is a simple example:

function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);

The output is as follows:

[12, 130, 44]

array.prototype.reduce()

The reduce() function simultaneously applies a function to two values of the array to reduce them to a single value. The direction of selection of values is from left to right.

Returns

A modified array.

Parameters

A callback function.

Description

The array.prototype.reduce() method is used to accumulate all values in an array to a single value by the operations performed in the callback function.

Here is a simple example:

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});

The callbacks are executed as follows:

 

previousValue

currentValue

index

array

return value

First call

0

1

1

[0, 1, 2, 3, 4]

1

Second call

1

2

2

[0, 1, 2, 3, 4]

3

Third call

3

3

3

[0, 1, 2, 3, 4]

6

Fourth call

6

4

4

[0, 1, 2, 3, 4]

10

array.prototype.forEach()

The array.prototype.forEach() method executes a function passed as a parameter for every element of the array.

Returns

The output of each function.

Parameter

A callback function to be called for every element of the array.

Description

The array.prototype.forEach() method calls functions of each element. Here is a simple example:

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Note elision, there is no member at 2 so it isn't visited
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

array.prototype.indexOf()

The array.prototype.indexOf() method returns the first index of an array.

Returns

An index.

Parameter

An array element.

Description

The array.prototype.indexOf() method returns the first index of an array. Here is a simple example:

var array = [2, 5, 9];
array.indexOf(9);     // 2
array.indexOf(7);     // -1 if not found

array.prototype.lastIndexOf()

The array.prototype.lastIndexOf() method returns the last index at which a given element is found inside an array.

Returns

It returns the last index of an array.

Parameter

An array element.

Description

As stated in the preceding descriptions, the array.prototype.lastIndexOf() function will return the last index of the specified element if found within the array. Here is a simple example:

var array = [2, 5, 9, 2];
array.indexOf(2);     // 3
array.indexOf(7);     // -1 if not found

array.prototype.every()

The array.prototype.every() method tests a function for every array element.

Returns

A Boolean true or false.

Parameter

A callback function to be applied on every element of the array.

Description

If every element in an array provides the testing function, then it returns true. Here is a simple example:

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

array.prototype.some()

This method tests if any element passes the test implemented by the provided function.

Returns

A Boolean True or False.

Parameters

A callback function.

Description

The array.prototype.some() method is similar to Array.prototype.every(), but here the condition is that at least one callback should return true.

A simple example is as follows:

function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

array.prototype.reduceRight()

The array.prototype.reduceRight() method applies a function simultaneously against two values of the array (from right to left) so as to reduce them to a single value.

Returns

A modified array.

Parameters

A callback function.

Description

This is exactly the same as reduce, but it starts from right and moves toward the left while accumulating the values.

Here is a simple example:

var total = [0, 1, 2, 3].reduceRight(function(a, b) {
  return a + b;
});

This returns the sum as 6.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.234.24