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.
There are two array types in JavaScript:
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
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:
indexOf
, push
, and forEach
In JavaScript, there are two ways to create arrays:
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");
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]];
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.
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
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]; }} }
An array has a prototype, length, and a constructor as its properties.
In JavaScript, the array length property returns the number of elements in an array.
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
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"];
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).
There are several methods that can be performed on arrays to obtain different results. Some of these methods are defined in the following sections.
The foreach()
method executes a function passed as a parameter for every element of the array.
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
This joins all elements into a string.
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
The pop()
method removes the last element of an array, just like a stack.
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'
In an array, the shift()
method removes the very first element and returns that element.
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'
The splice()
method is also used to add new elements to an array by removing existing elements.
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
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.
The map()
method creates a new array on the result values from each iteration.
The filter()
function creates a new or modified array that consist of values that are processed by the function.
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.
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 |
|
|
|
|
|
Second call |
|
|
|
|
|
Third call |
|
|
|
|
|
Fourth call |
|
|
|
|
|
The
array.prototype.forEach()
method executes a function passed as a parameter for every element of the array.
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
The
array.prototype.lastIndexOf()
method returns the last index at which a given element is found inside an array.
This method tests if any element passes the test implemented by the provided function.
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
18.225.234.24