• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Arrays

JS Arrays

Welcome to another tutorial, here you will learn to create and manipulate arrays in JavaScript.

 

What is an Array

JavaScript arrays as complex variables allow more than one value or a group of values stored under a single variable name. It stores any valid value, encompassing strings, numbers, objects, functions, and even other arrays, hence making it possible to create more complex data structures such as an array of objects or an array of arrays.

To store the name of colors in a variable in your JavaScript code could look something like this:

var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";

But to store the state or city names of a country in variables that may be a hundred in a separate variable is quite hard and boring. Hence, it will be a herculean task to keep track of many variables simultaneously. In this case, the array comes into play and solves the problem by providing an ordered structure for storing a group of values or multiple values.


Creating an Array

In JavaScript, enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax is the simplest way of creating an array.

var myArray = [element0, element1, ..., elementN];

To create an array, the Array() constructor as shown in the following syntax can be used. But, the previous syntax is recommended for the sake of simplicity. 

var myArray = new Array(element0, element1, ..., elementN);

Here are some examples of arrays created using an array literal syntax:

var colors = ["Red", "Green", "Blue"]; 
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

Note: An ordered collection of values is called Array and each value is called an element. Each element occupies a numeric position in an array, known as its index.

 

Accessing the Elements of an Array

Array elements can be accessed by their index using the square bracket notation, and the index number is used to represent an element's position.

Array indexes are zero-based which means that the first item of an array isn’t stored at index 1, but 0. Hence, the second item is stored at index 1, and so on. Array indexes start at 0 and increase to the number of elements minus 1. In addition, an array of five elements would have indexes from 0 to 4.

The following example will show you how to get individual array elements by their index.

Example:

<html>
<head></head>
<body>
  <script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits[0]); // Prints: Apple
document.write("<br>"+fruits[1]); // Prints: Banana
document.write("<br>"+fruits[2]); // Prints: Mango
document.write("<br>"+fruits[fruits.length - 1]); // Prints: Papaya
  </script>
</body>
</html>

Try with example

 

Note: In JavaScript, arrays are significantly a special type of object which has numeric indexes as keys. For arrays, the type of operator will return "object".

 

Getting the Length of an Array

The length of an array, which is the total number of elements contained in the array, is returned by the length property. Array length is constantly far greater than the index of any of its elements.

Example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.length); // Prints: 5

Try with example
 

Looping Through Array Elements

In sequential order, the for-of loop can be used to access each element of an array, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(var i = 0; i < fruits.length; i++) {    
    document.write(fruits[i] + "<br>"); // Print array element
}

Try with example

ECMAScript 6 which is a for-of loop has introduced a simpler way to iterate over array elements. To initialize and keep track of the loop counter variable in this loop isn’t mandatory (i).

Here's the same example is rewritten using the for-of loop:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Iterates over array elements
for(var fruit of fruits) {    
    document.write(fruit + "<br>"); // Print array element
}

Try with example

 

The for-in loop can be used to iterate over the array of elements, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
// Loop through all the elements in the array 
for(var i in fruits) {  
    document.write(fruits[i] + "<br>");
}

Try with example

 

Note: Where the index order is important the for-in loop shouldn’t be used to iterate over an array. The for-in loop is optimized for iterating over an object's properties, hence, for loop with a numeric index or for-of loop should be used.

 

Adding New Elements to an Array

Simply use the push() method to add a new element at the end of an array, like this:

Example:

<html>
<head></head>
<body>
  <script>
  var colors = ["Red", "Green", "Blue"]; 
colors.push("Yellow");
 
document.write(colors); // Prints: Red,Green,Blue,Yellow
document.write(colors.length); // Prints: 4
  </script>
</body>
</html>

Try with example

Similarly, use the unshift() method to add a new element at the beginning of an array, like this:

Example:

var colors = ["Red", "Green", "Blue"]; 
colors.unshift("Yellow");
 
document.write(colors); // Prints: Yellow,Red,Green,Blue
document.write(colors.length); // Prints: 4

Try with example

 

You can also add multiple elements at once using the push() and unshift() methods, like this:

Example:

var colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");
 
document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
document.write(colors.length); // Prints: 7

Try with example


Removing Elements from an Array

The pop() method can be used to remove the last element from an array. This specific method returns the value that was popped out. Here's an example:

Example:

var colors = ["Red", "Green", "Blue"];
var last = colors.pop();
 
document.write(last); // Prints: Blue
document.write(colors.length); // Prints: 2

Try with example

 

Similarly, the first element can be removed from an array using the shift() method. This method returns the value that was shifted out as well. Here's an example:

var colors = ["Red", "Green", "Blue"];
var first = colors.shift();
 
document.write(first); // Prints: Red
document.write(colors.length); // Prints: 2

Try with example

 

Tip: “The push()” and “pop()” methods runs quite faster than “unshift()” and “shift()”. This is simply because the push() and pop() methods allow the addition and removal of elements at the end of an array causing the elements to remain in their initial position. On the other hand, unshift() and shift() methods allow the addition and removal of elements at the beginning of the array causing re-indexing of the whole array.

 

Adding or Removing Elements at Any Position

Being a very versatile array method, the splice() method allows addition or removal of elements from any index, using the syntax arr.splice(startIndex, deleteCount, elem1, …elemN).

This method takes three parameters and these parameters are as follows: 

  • The first parameter is required and it is the index at which to start splicing the array.
  • The second parameter is optional and it is the number of elements to remove. Zero (0) can be used to avoid removing any elements.
  • The third parameter is equally optional and it is a set of replacement elements.

 

The following example shows how it works:

Example:

var colors = ["Red", "Green", "Blue"];
var removed = colors.splice(0,1); // Remove the first element
 
document.write(colors); // Prints: Green,Blue
document.write(removed); // Prints: Red (one item array)
document.write(removed.length); // Prints: 1
 
removed = colors.splice(1, 0, "Pink", "Yellow"); // Insert two items at position one
document.write(colors); // Prints: Green,Pink,Yellow,Blue
document.write(removed); // Empty array
document.write(removed.length); // Prints: 0
 
removed = colors.splice(1, 1, "Purple", "Voilet"); // Insert two values, remove one
document.write(colors); //Prints: Green,Purple,Voilet,Yellow,Blue
document.write(removed); // Prints: Pink (one item array)
document.write(removed.length); // Prints: 1

Try with example

As seen from the above example, The splice() method returns an array of the deleted elements, or an empty array because no elements were deleted. In case the second argument, not the first argument is omitted, all elements from the start to the end of the array are removed. The splice() method modifies the array on which it is called on, unlike slice() and concat() methods.

 

Creating a String from an Array

Situations may arise where a string needs to be created by joining the elements of an array. The join() method can be used to do this. This method takes an optional parameter which is a separator string and is added in between each element. The JavaScript will use comma [,] by default if you omit the separator. The following example shows how it works:

Example:

<html>
<head></head>
<body>
  <script>
  var colors = ["Red", "Green", "Blue"];
 
  document.write(colors.join()); // Prints: Red,Green,Blue
  document.write("<br>");
  document.write(colors.join("")); // Prints: RedGreenBlue
  document.write("<br>");
  document.write(colors.join("-")); // Prints: Red-Green-Blue
  document.write("<br>");
  document.write(colors.join(", ")); // Prints: Red, Green, Blue
  </script>
</body>
</html>

Try with example

An array can also be converted to a comma-separated string using the toString(). This method unlike join() does not accept the separator parameter. Here's an example:

<html>
<head></head>
<body>
  <script>
  	var colors = ["Red", "Green", "Blue"];
	document.write(colors.toString()); // Prints: Red,Green,Blue
  </script>
</body>
</html>

Try with example


Extracting a Portion of an Array

Slice() method can be used to extract out a portion of an array or subarray without affecting the original array. This method takes 2 parameters and they are as follows:

  • Start index: This is the index at which to begin extraction.
  • An optional end index: This is the index before which to end extraction, like arr.slice(startIndex, endIndex).

Here's an example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango

Try with example

All elements to the end of the array are extracted if the endIndex parameter is omitted. In case negative indexes or offsets have been specified the slice() method can be used to extract the elements from the end of an array, rather than the beginning.

For example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya
document.write(fruits.slice(-2)); // Prints: Orange,Papaya
document.write(fruits.slice(2, -1)); // Prints: Mango,Orange

Try with example

 

Merging Two or More Arrays

To merge or combine two or more arrays the contact() method can be used. This method does not alter the existing arrays, rather it returns a new array.

For example:

var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
 
// Creating new array by combining pets and wilds arrays
var animals = pets.concat(wilds); 
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra

Try with example

 

As shown in the example below, the contact() method can take any number of array arguments, so an array from any number of other arrays can be created.

var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
var bugs = ["Ant", "Bee"];
 
// Creating new array by combining pets, wilds and bugs arrays
var animals = pets.concat(wilds, bugs); 
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

Try with example

 

Searching Through an Array

Simply use the indexOf() and lastIndexOf() to search an array for a specific value. Both methods return an index representing the array element in case the value is found. Otherwise, -1 is returned if the value is not found. The indexOf() method and the lastIndexOf() returns the first one found and the last one found when used respectively.

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
 
document.write(fruits.indexOf("Apple")); // Prints: 0
document.write(fruits.indexOf("Banana")); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1

Try with example

These two methods also accept an optional integer parameter from the index which specifies the index within the array at which to start the search.

Here's an example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
// Searching forwards, starting at from- index
document.write(arr.indexOf(1, 2)); // Prints: 3
 
// Searching backwards, starting at from index
document.write(arr.lastIndexOf(1, 2)); // Prints: 0

Try with example

You can make of use the includes() method to find out whether certain elements are included in an array or not. Aside from the fact that this method returns true or false instead of an index number, it takes the same parameters as indexOf() and lastIndexOf() methods. 

For example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
document.write(arr.includes(1)); // Prints: true
document.write(arr.includes(6)); // Prints: false
document.write(arr.includes(1, 2)); // Prints: true
document.write(arr.includes(3, 4)); // Prints: false

Try with example

 

The JavaScript find() method which is newly introduced in ES6 can be used to search an array based on certain conditions. The return of this method which is the value of the first element in the array satisfies the provided testing function. If not satisfied it returns undefined.

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.find(function(element) {
  return element > 4;
});
document.write(result); // Prints: 5

Try with example

 

One more significant method that is similar to find() is the findIndex() method which returns the index of a found element in the array instead of its value.

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.findIndex(function(element) {
  return element > 6;
});
document.write(result); // Prints: 8

Try with example

 

The find() method solely searches for the first element that satisfies the provided testing function. However, to find out all the matched elements use the filter() method because it creates a new array with all the elements that successfully pass the given test. 

The following example will show you how this actually works:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];
 
var result = arr.filter(function(element) {
  return element > 4;
});
document.write(result); // Prints: 5,7
document.write(result.length); // Prints: 2

Try with example

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.