- JavaScript Arrays
- Why Use Arrays?
- Creating an Array
- Example
- Example
- Example
- Using the JavaScript Keyword new
- Example
- Accessing Array Elements
- Changing an Array Element
- Example
- Converting an Array to a String
- Example
- Access the Full Array
- Example
- Arrays are Objects
- Array:
- Object:
- Array Elements Can Be Objects
- Array Properties and Methods
- The length Property
- Example
- Accessing the First Array Element
- Example
- Accessing the Last Array Element
- Example
- Looping Array Elements
- Example
- Example
- Adding Array Elements
- Example
- Example
- Example
- Associative Arrays
- Example
- Example:
- The Difference Between Arrays and Objects
- When to Use Arrays. When to use Objects.
- JavaScript new Array()
- How to find the index of an array element in JavaScript
- How to find the index of an array element in JavaScript
- How to find the index of an array element using the indexOf() method
- Example
- How to find the index of an array element using the lastIndexOf() method
- Example
- How to find the index of an array element using the findIndex() method
- Example
- Conclusion
JavaScript Arrays
An array is a special variable, which can hold more than one value:
Why Use Arrays?
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
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.
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const.
Example
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
You can also create an array, and then provide the elements:
Example
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
The two examples above do exactly the same.
There is no need to use new Array() .
For simplicity, readability and execution speed, use the array literal method.
Accessing Array Elements
You access an array element by referring to the index number:
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.Changing an Array Element
This statement changes the value of the first element in cars :
Example
Converting an Array to a String
The JavaScript method toString() converts an array to a string of (comma separated) array values.
Example
const fruits = [«Banana», «Orange», «Apple», «Mango»];
document.getElementById(«demo»).innerHTML = fruits.toString();
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.
Arrays use numbers to access its «elements». In this example, person[0] returns John:
Array:
Objects use names to access its «members». In this example, person.firstName returns John:
Object:
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:
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Array methods are covered in the next chapters.
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 Array Element
Example
Accessing the Last Array Element
Example
Looping Array Elements
One way to loop through an array, is using a for loop:
Example
const fruits = [«Banana», «Orange», «Apple», «Mango»];
let fLen = fruits.length;
You can also use the Array.forEach() function:
Example
const fruits = [«Banana», «Orange», «Apple», «Mango»];
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
Example
const fruits = [«Banana», «Orange», «Apple»];
fruits.push(«Lemon»); // Adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example
const fruits = [«Banana», «Orange», «Apple»];
fruits[fruits.length] = «Lemon»; // Adds «Lemon» to fruits
Adding elements with high indexes can create undefined «holes» in an array:
Example
const fruits = [«Banana», «Orange», «Apple»];
fruits[6] = «Lemon»; // Creates undefined «holes» in fruits
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
const person = [];
person[0] = «John»;
person[1] = «Doe»;
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return «John»
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results.
Example:
const person = [];
person[«firstName»] = «John»;
person[«lastName»] = «Doe»;
person[«age»] = 46;
person.length; // Will return 0
person[0]; // Will return undefined
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.
JavaScript new Array()
JavaScript has a built-in array constructor new Array() .
But you can safely use [] instead.
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
The new keyword can produce some unexpected results:
How to find the index of an array element in JavaScript
The index of an array element represents the position of the element in the array. The index number can be retrieved by using the indexOf(), lastIndexOf(), and findIndex() methods. All of these methods are used for tracing the index of array elements. This guide provides an insight into the possible methods that can be used to get the index number of a specific element in an array. The following learning outcomes are expected when you go through this article:
- indexOf() method in JavaScript
- lastIndexOf() method in JavaScript
- findIndex() method in JavaScript
How to find the index of an array element in JavaScript
The array element can be traced by using the indexOf(), lastIndexOf(), and findIndex() methods. This section provides the working of each method with examples.
How to find the index of an array element using the indexOf() method
The indexOf() method traces the first occurrence of a specific element and returns the index.
- The array(or an array itself) refers to the array variable where the element would be traced for an index number.
- The start value represents an index number from where the indexOf() method will start searching.
The start value can be set to negative or positive.
- If the value is positive, then the indexOf() method would start from that index.
- If the value is negative then the search would start after calculating the following expression. (length of array + (negative value)).
Example
The usage of the indexOf() method is described to get the index of a specific element in an array variable.
arr = [ «apple» , «guava» , «banana» , «peach» , «banana» ] ;
console. log ( arr. indexOf ( «banana» ) ) ;
console. log ( arr. indexOf ( «banana» , — 1 ) ) ;
The above code creates an array. We have used the indexOf() method on the “banana” element of that array . The first method traces the banana element and returns the index number of its first occurrence. Whereas the second indexOf() method takes -1 for starting value, the sorting will start from index=(4+ (-1)=3).
The output shows the index of the first occurrence of “banana” without any starting condition and the second method takes the starting condition “-1” and will start the index counting from (4+(-1)).
How to find the index of an array element using the lastIndexOf() method
As the name of this method represents, it would return the last occurrence of an element.
The syntax is described as, the array is an array variable (or array itself) and the element is contained inside it.
Example
Here, the lastIndexOf() method is applied to get the index of a specific element
num = [ 3 , 4 , 3 , 5 , 9 , 3 , 12 ] ;
console. log ( num. lastIndexOf ( 3 ) ) ;
console. log ( num. lastIndexOf ( 30 ) ) ;
The above code creates a numeric array and the lastIndexOf() method is applied to that array to trace the last index of “3“. Additionally, we have applied the lastIndexOf() method on a number “30” (that does not belong to an array).
The output shows that the last index number of an element “3” is “5” and as the number “30” does not belong to the array, the result is “-1“.
How to find the index of an array element using the findIndex() method
By using findIndex(), you will be able to get the index of an element that meets the criteria you specified. Once an element satisfies the function(criteria), the findIndex() method stops executing and returns the index of that element only.
The findIndex() method accepts two arguments, one is a function (a test function to run on each element until any element satisfies the condition) and the other is This-Value.
The function accepts the following parameters
Current-Value: It refers to the value of a current element
Index: This is an optional parameter and represents the index of the current element
Arr: Refers to the array of the current element
Example
The following JS code executes the findIndex() method to get the index number of an element that satisfies the condition.
console. log ( ( num. findIndex ( find ) ) ) ;
In the above code, an array named “num” is initialized and the find() function is applied on each element of num, and it returns values greater than 10. After that, the “find()” method is called from the “findIndex()” function to get the index of the first element that is greater than “10“.
The “find()” method returns all the numbers that are greater than “10” and the “findIndex()” method picks only the index of the first number (that is 20 in our case).
Conclusion
JavaScript provides various methods such as indexOf(), lastIndexOf(), and findIndex() methods to get the index number of an element in an array. This guide provides syntaxes and the working of each above-mentioned method. To get the first occurrence index of an element, the indexOf() method is used. However, the lastInexOf() would give you the index of the last occurrence of any specific element. As opposed to those methods, findIndex() returns the index number of the first element that satisfies a given function (which is passed as a parameter to findIndex()).