top of page

JavaScript Arrays

JavaScript Arrays


JavaScript arrays are used to store multiple values in a single variable.


Example:


What is an Array?

  • An array is a special variable, which can hold more than one value at a time.

  • An array can hold many values under a single name, and you can access the values by referring to an index number.


Creating an Array


Using an array literal is the easiest way to create a JavaScript Array.


Syntax:

var array_name = [ item1, item2, ...];      


Example:

  • Spaces and line breaks are not important. A declaration can span multiple lines.

  • Putting a comma after the last element (like "BMW",)  is inconsistent across browsers.

  • IE 8 and earlier will fail.


Using the JavaScript Keyword new


The JavaScript new keyword is used to create a new array and to assign values to it.


Example:

  • The above two examples are the same.

  • For simplicity, readability and execution speed, the first one (the array literal method) is used.


Access the Elements of an Array


An array element can be accessed by referring to its index number.


Example:

Note:- Array indexes start with 0.

[0] is the first element. [1] is the second element.


Changing an Array Element


The values of an array can be changed.


Example:

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:


Example:


Arrays are Objects

  • Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

  • But, JavaScript arrays are best described as arrays.

Array:

  • Arrays use numbers to access its "elements".

  • In this example, person[0] returns Mukesh.

Example:


Object:

  • Objects use names to access its "members".

  • In this example, person.fname returns Mukesh.

Example:


Array Elements Can Be Objects

  • JavaScript variables can be objects. Arrays are special kinds of objects.

  • Because of this, you can have variables of different types in the same Array.

  • You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars;


Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:


The length Property


The length property of an array returns the length of an array (the number of array elements).


Example:

The length property is always one more than the highest array index.


Accessing the First and Last Array Element


Example:


Associative Arrays

  • Many programming languages support arrays with named indexes.

  • Arrays with named indexes are called associative arrays (or hashes).

  • JavaScript does not support arrays with named indexes.

  • In JavaScript, arrays always use numbered indexes.  

Example:

Note:-

  • If you use named indexes, JavaScript will redefine the array to a standard object.

  • After that, some array methods and properties will produce incorrect results.


The Difference Between Arrays and Objects

  • In JavaScript, arrays use numbered indexes.  

  • In JavaScript, objects use named indexes.

  • Arrays are a special kind of objects, with numbered indexes.


When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.

  • You should use objects when you want the element names to be strings (text).

  • You should use arrays when you want the element names to be numbers.


Avoid new Array()


There is no need to use the JavaScript's built-in array constructor new Array().

Use [] instead.

These two different statements both create a new empty array named points:

var points = new Array();     // Bad var points = [];               // Good 

JavaScript Array Methods


Converting Arrays to Strings


The JavaScript method toString() converts an array to a string of (comma separated) array values.


Example:


Popping and Pushing


When you work with arrays, it is easy to remove elements and add new elements.


This is what popping and pushing is:

  • Popping items out of an array, or

  • pushing items into an array.

Popping

  • The pop() method removes the last element from an array.

  • The pop() method returns the value that was "popped out".

Example:



Pushing

  • The push() method adds a new element to an array (at the end).

  • The push() method returns the new array length.

Example:


Shifting Elements

  • Shifting is equivalent to popping, working on the first element instead of the last.

  • The shift() method removes the first array element and "shifts" all other elements to a lower index.

  • The shift() method returns the string that was "shifted out".

  • The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.

  • The unshift() method returns the new array length.

Example:


Changing Elements

  • Array elements are accessed using their index number.

  • Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the third ...

  • The length property provides an easy way to append a new element to an array.

Example:


Deleting Elements


Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete.


Example:

Using delete may leave undefined holes in the array. Use pop() or shift() instead.


Splicing an Array

  • The splice() method can be used to add new items to an array.

  • The splice() method returns an array with the deleted items.

Example:


JavaScript Sorting Arrays


Sorting an Array


The sort() method sorts an array alphabetically:


Example:


Reversing an Array

  • The reserve() method reverses the elements in an array.

  • You can use it to sort an array in descending order.

Example:


Numeric Sort

  • By default, the sort() function sorts values as strings.

  • This works well for strings.

  • However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

  • Because of this, the sort() method will produce incorrect result when sorting numbers.

Example:


Find the Highest (or Lowest) Array Value


There are no built-in functions for finding the max or min value in an array.

However, after you have sorted an array, you can use the index to obtain the highest and lowest values.


Example:

Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value.


My Min / Max JavaScript Methods


This function loops through an array comparing each value with the highest value found:


Example:

This function loops through an array comparing each value with the lowest value found:



JavaScript Array Iteration Methods


Array iteration methods operate on every array item.


Array.forEach()


The forEach() method calls a function (a callback function) once for each array element.

Note that the function takes 3 arguments:

  • The item value

  • The item index

  • The array itself

Example:



Array.map()

  • The map() method creates a new array by performing a function on each array element.

  • The map() method does not execute the function for array elements without values.

  • The map() method does not change the original array.

Example:


Note that the function takes 3 arguments:

  • The item value

  • The item index

  • The array itself

When a callback function uses only the value parameter, the index and array parameters can be omitted


Array.filter()

  • The filter() method creates a new array with array elements that passes a test.

  • This example creates a new array from elements with a value larger than 18:

Example:


Note that the function takes 3 arguments:

  • The item value

  • The item index

  • The array itself


Array.reduce()

  • The reduce() method runs a function on each array element to produce (reduce it to) a single value.

  • The reduce() method works from left-to-right in the array. See also reduceRight().

  • The reduce() method does not reduce the original array.

Example:

Note that the function takes 4 arguments:

  • The total (the initial value / previously returned value)

  • The item value

  • The item index

  • The array itself


Array.reduceRight()

  • The reduceRight() method runs a function on each array element to produce (reduce it to) a single value.

  • The reduceRight() works from right-to-left in the array. See also reduce().

  • The reduceRight() method does not reduce the original array.

Example:

Note that the function takes 4 arguments:

  • The total (the initial value / previously returned value)

  • The item value

  • The item index

  • The array itself


Commentaires


bottom of page