But it’s also good to know that two-dimensional arrays (2D arrays) exist in JS.
What is a Two-Dimensional Array?
A two-dimensional array, also known as a 2D array, is a collection of data elements arranged in a grid-like structure with rows and columns. Each element in the array is referred to as a cell and can be accessed by its row and column indices/indexes.
But there is a limitation. It is important to note that two-dimensional arrays have a fixed size. This means that once they are created, the number of rows and columns should be fixed. Also, each row should have a similar number of elements (columns).
For example, the array below has three rows and four elements:
The limitation is that with jagged arrays, you don't get to specify a fixed row and column. This means that a jagged array could have m rows, each having different numbers of elements.
At this point, you may ask yourself about the importance of a 2D array, especially if this is your first time reading about 2D arrays.
- They allow for the efficient storage and manipulation of large amounts of data, such as in image or video processing, scientific simulations, and spreadsheet applications.
- Two-dimensional arrays also enable the use of matrix operations, such as matrix multiplication and transposition, which can simplify complex calculations and make code more readable.
- Two-dimensional arrays can represent mathematical matrices in linear algebra and a wide range of data, such as graphs, maps, and tables.
- Two-dimensional arrays are commonly used in applications that involve data tables, image processing, and game development.
You can access the elements of a two-dimensional array using two indices, one for the row and one for the column. Suppose you have the following two-dimensional array:
The above is a jagged array in which each element holds the student's name, test score, exam score, and grade. You can access specific elements using the row and column index as seen in the syntax below:
To better understand this, let’s convert the two-dimensional array above to a table using console.table(arrayName) .
Note: make sure that you replace arrayName with the name of your 2D array. In my case, it is MathScore .
You will get an output like this, showing the row and column index. Remember that arrays are zero-indexed, meaning items are referenced from 0, not 1.
Please note that the (index) column and row are for the illustration that indicates the indices/indexes of the inner array.
You use two square brackets to access an element of the two-dimensional or multi-dimensional array. The first accesses the rows, while the second accesses the element in the specified row.
How to access the first and last elements of a 2D array
Sometimes you might need to find the first and last elements of a two-dimensional array. You can do this using the first and last index of both the rows and columns.
The first element will always have the row and column index of 0, meaning you will use arrayName, .
The index of the last element can be tricky, however. For example, in the example above, the first element is ‘John Doe’ while the last is ‘B’:
How to add all elements of a 2D array
In some situations, all the elements of your 2D array can be numbers, so you may need to add them together and arrive at just one digit. You can do this using a nested loop. You will first loop through the rows, then, for each row, you loop through its elements.
You can manipulate 2D arrays just like one-dimensional arrays using general array methods like pop, push, splice and lots more.
Let’s start by learning how to add/insert a new row and element to the 2D array.
How to insert an element into a 2D array
You can add an element or many elements to a 2D array with the push() and unshift() methods.
The push() method adds elements(s) to the end of the 2D array, while the unshift() method adds element(s) to the beginning of the 2D array.
When you console.log() or console.table() the array, you will see that the new rows have been added:
You can also add elements to the inner array, but it’s wrong to push to just one inner array without affecting all the array elements. This is because two-dimensional arrays are meant to have the same number of elements in each element array.
Instead of affecting one array element, you can add elements to all element arrays at once:
This will return:
You can also use the unshift() method to insert the element at the beginning and the splice() method to insert at the middle of the array:
In the above, 1 is the position where you want the new array to be inserted (remember it is zero-indexed), 0 is used so it removes no element, and then the third parameter is the array to be added.
This is the output:
How to remove an element from a 2D array
You can also remove element(s) from the beginning and end of a 2D array with the pop() and shift() methods. This is similar to how the push() and unshift() methods work, but you do not add any parameters to the methods this time.
When you console.log() or console.table() the array, you will see that the first and last array elements have been removed:
You can also remove elements from each array element:
You can also use the shift() method to remove the element at the beginning and the splice() method to remove array elements from specific positions:
In the code above, you remove one item from position index 2 of the MathScore 2D array. This will output:
There are two options for creating a multi-dimensional array. You can create the array manually with the array literal notation, which uses square brackets  to wrap a list of elements separated by commas. You can also use a nested loop.
How to create a 2D array using an array literal
This is just like the examples we have been considering using the following syntax:
For example, below is a 2D array that holds information about each student’s math score and grade:
How to create a 2D array using a nested for loop
There are many approaches to doing this. But generally, you create a nested loop where the first loop will loop through the rows while the second loop will loop through the elements in the inner array (columns):
In the code above, you will first loop through the rows. For each row, it will create an empty array within the original array declared and stored in variable arr . You will then create a nested loop to loop through the columns and add individual elements.
In this example, the index for j is used and will output:
You can decide to create a number, initialize with 0, and then increase as you loop through so you don’t have the same number for all elements:
You can also decide to create a function that accepts these values as arguments:
This is very similar to how you do it with one-dimensional arrays, where you can update an array’s value by using the index to assign another value.
You can use the same approach to change an entire row or even individual elements:
This will replace the value of index 1 with this new array:
You can update individual elements by tracking the row and column indices and updating their values:
This will change the name on the row with index 2 to “Jack Jim”, as seen below:
Have fun coding!
You can access over 150 of my articles by visiting my website . You can also use the search field to see if I've written a specific article.
Frontend Developer & Technical Writer
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
To declare an empty multidimensional array, you use the same syntax as declaring one-dimensional array:
The following example defines a two-dimensional array named activities :
In the activities array, the first dimension represents the activity and the second one shows the number of hours spent per day for each.
To show the activities array in the console, you use the console.table() method as follows:
The following illustrates the output:
Note that the (index) column is for the illustration that indicates the indices of the inner array.
To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.
The following example returns the second element of the first inner array in the activities array above:
You can use the Array methods such as push() and splice() to manipulate elements of a multidimensional array.
For example, to add a new element at the end of the multidimensional array, you use the push() method as follows:
To insert an element in the middle of the array, you use the splice() method. The following inserts an element in the second position of the activities array:
Here is the output:
This example calculates the percentage of the hours spent on each activity and appends the percentage to the inner array.
The following shows the output in the console:
To remove an element from an array, you use the pop() or splice() method.
For example, the following statement removes the last element of the activities array.
Similarly, you can remove the elements from the inner array of the multidimensional array by using the pop() method. The following example removes the percentage element from the inner arrays of the activities array.
To iterate a multidimensional array, you use a nested for loop as in the following example.
The first loop iterates over the elements of the outer array and the nested loop iterates over elements of the inner array.
The following shows the output of the script in the console:
Or you can use the forEach() method twice:
Updated: March 14, 2023
This YouTube channel is packed with awesome videos for coders!
What are Multidimensional Arrays?
Think of a multidimensional array as a matrix or a table with rows and columns. For instance, a two-dimensional array represents a table with rows and columns, and a three-dimensional array can be visualized as a cube.
Creating a Multidimensional Array
Here, we’ve created a 3x3 matrix using an array of arrays. The outer array contains three arrays, each representing a row, and these inner arrays have three elements each, representing the columns.
Now, if we want to access an element from the matrix, we can use the following syntax:
In this example, matrix 1 returns the second row (remember, arrays are zero-indexed), and 2 after that accesses the third element in that row, which is 6.
Working with Multidimensional Arrays
Let’s now explore some common operations we might want to perform on multidimensional arrays.
Iterating Over Elements To loop through all the elements of a 2D array, we can use nested for loops like this:
This code will output all the elements in the matrix one by one.
To add elements to a multidimensional array, we can use the push method like we would with a regular array. Let’s add a new row to our matrix:
Now, our matrix looks like this:
We can remove elements from a multidimensional array using the splice method. To remove the last row from the matrix, we can do the following:
Now, our matrix is back to its original form:
And there you have it!
Frequently asked questions
A multidimensional array is an array containing one or more arrays within it. These nested arrays can have their own arrays, allowing for multiple levels of data storage, resembling a matrix or a table.
How do you define a multidimensional array?
Can you have arrays with different lengths in a multidimensional array?
How do you access elements in a multidimensional array?
Elements in a multidimensional array can be accessed using multiple indices. The first index refers to the initial array, and the subsequent indices refer to the elements within the inner arrays. Example: multiArray 0 would access the element 2 in the array provided in A2.
How do you loop through a multidimensional array?
You can loop through a multidimensional array by using nested loops. An outer loop iterates through the main array while an inner loop goes through each individual sub-array.
Can you use methods like push or pop on multidimensional arrays?
Yes, methods like push and pop can be used with multidimensional arrays, but they will affect only the array you are directly interacting with, either the main array or one of the sub-arrays, depending on the syntax.
How do you add items to a multidimensional array?
To add items to a specific array within a multidimensional array, target it with indices and use methods like push for adding elements. Example: multiArray 1 .push(10); would add the number 10 to the second array in multiArray.
Can multidimensional arrays contain different types of data?
Yes, similar to regular arrays, multidimensional arrays can store different types of data, including strings, numbers, objects, and even functions, within different sub-arrays.
How can I remove an element from a sub-array in a multidimensional array?
You can remove elements from a sub-array using methods like splice(), targeting the sub-array with the appropriate indices. Example: multiArray.splice(1, 1); would remove the second element from the third array in multiArray.
Understanding multidimensional arrays is essential for handling complex data structures in programming.
Popular examples, reference materials, learn python interactively, js introduction.
- Getting Started
- JS Variables & Constants
- JS console.log
- JS Type Conversions
JS Control Flow
- JS Comparison Operators
- Variable Scope
- JS Multidimensional Array
Exceptions and Modules
- Destructuring Assignment
- Iterators and Iterables
A multidimensional array is an array that contains another array. For example,
Create a Multidimensional Array
Here, both example 1 and example 2 creates a multidimensional array with the same data.
Access Elements of an Array
You can access the elements of a multidimensional array using indices (0, 1, 2 …) . For example,
You can think of a multidimensional array (in this case, x), as a table with 3 rows and 2 columns.
Add an Element to a Multidimensional Array
You can use the Array's push() met hod or an indexing notation to add elements to a multidimensional array.
Adding Element to the Outer Array
Adding Element to the Inner Array
You can also use the Array's splice() m ethod to add an element at a specified index. For example,
Remove an Element from a Multidimensional Array
You can use the Array's pop() met hod to remove the element from a multidimensional array. For example,
Remove Element from Outer Array
Remove Element from Inner Array
You can also use the splice() method to remove an element at a specified index. For example,
- Iterating over Multidimensional Array
You can iterate over a multidimensional array using the Array's forEach() method to iterate over the multidimensional array. For example,
The first forEach() method is used to iterate over the outer array elements and the second forEach() is used to iterate over the inner array elements.
You can also use the for...of loop to iterate over the multidimensional array. For example,
You can also use the for loop to iterate over a multidimensional array. For example,
Table of Contents
- Create Multidimensional Array
- Access Elements of Array
- Add Element to Multidimensional Array
- Remove from Multidimensional Array
Sorry about that.
A multidimensional array is an array that contains one or more arrays as elements. In other words, it is an array of arrays. Among multidimensional arrays, two-dimensional arrays (or 2D arrays) are widely used because they can represent many types of data that have a grid-like or tabular structure. Their elements are organized into rows and columns
Using square brackets (the array literal notation)
For example, you can create a 2D array with 3 rows and 4 columns like so:
You can access and modify the elements of a multidimensional array by using indexes. For instance, to get the value of 6 from the above array, you can use array . To change it to 10 , you can use array = 10 .
Using the Array() constructor
The preceding approach seems neat and intuitive. However, it isn’t the only possible way. You can also use the new Array() constructor to create an array and then assign each element as another array.
Using nested loops
You can make use of nested loops to create an empty multidimensional array and then fill it with values. This techniqeu is useful when you need to programmatically create an array with a large number of rows and columns.
Output (yours might be different from mine because the code use Math.random() ):
Search tutorials, examples, and resources
- PHP programming
- Symfony & Doctrine
- Laravel & Eloquent
- Tailwind CSS
- 90% Refund @Courses
- DSA with JS - Self Paced
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Cheat Sheet
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
- JS Web Technology
- Solve Coding Problems
- What is an asynchronous request in AJAX ?
- How to find email in database using Ajax ?
- What are Discriminated union types?
- How to get Google App Script to skip an error and go to the next item ?
Here arr1, arr2, …arr5 are some 1D arrays that are inside the salary array.
Here, the salary array works like a multidimensional array. This notations are known as array literals.
Accessing the element of the salary array:
- To access the array element we need a simple index-based notation
- For many iteration, we need to use loop to access the elements,
Adding elements in Multidimensional Array: Adding elements in multi-dimensional arrays can be achieved in two ways in inner array or outer array . The inner array can be done in two different ways.
- We can use simple square bracket notation to add elements in multidimensional array.
- We can use push() method to add elements in the array.
- Adding elements to outer array: It is much similar to previous methods.
Removing elements in Multidimensional Array: We can use pop() methods to remove elements from inner-arrays, and also use pop() method for removing a entire inner array.
Example 1: Below is the example
Example 2: Below is the example.
Example 3: Below is the example.
Example 4: Below is the example.
Example 5: Below is the example.
Example 6: Below is the example.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !
Please Login to comment...
- Technical Scripter
- Web Technologies
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
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?
The solution is an array!
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
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const .
Spaces and line breaks are not important. A declaration can span multiple lines:
You can also create an array, and then provide the elements:
The following example also creates an Array, and assigns values to it:
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.
 is the first element.  is the second element.
Changing an Array Element
This statement changes the value of the first element in cars :
Converting an Array to a String
Access the Full Array
Arrays are Objects
Arrays use numbers to access its "elements". In this example, person returns John:
Objects use names to access its "members". In this example, person.firstName returns John:
Array Elements Can Be 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
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).
The length property is always one more than the highest array index.
Accessing the First Array Element
Accessing the last array element, looping array elements.
One way to loop through an array, is using a for loop:
You can also use the Array.forEach() function:
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined "holes" in an array:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
After that, some array methods and properties will produce incorrect results .
The difference between arrays and objects.
Arrays are a special kind of objects, with numbered indexes.
When to Use Arrays. When to use Objects.
- 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 .
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:
A Common Error
is not the same as:
How to Recognize an Array
A common question is: How do I know if a variable is an array?
The instanceof operator returns true if an object is created by a given constructor:
Complete Array Reference
For a complete Array reference, go to our:
The reference contains descriptions and examples of all Array properties and methods.
Test Yourself With Exercises
Get the value " Volvo " from the cars array.
Start the Exercise
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
There are two syntaxes for creating an empty array:
Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
Array elements are numbered, starting with zero.
We can get an element by its number in square brackets:
We can replace an element:
…Or add a new one to the array:
The total count of the elements in the array is its length :
We can also use alert to show the whole array.
An array can store elements of any type.
An array, just like an object, may end with a comma:
The “trailing comma” style makes it easier to insert/remove items, because all lines become alike.
Get last elements with “at”
Let’s say we want the last element of the array.
Some programming languages allow the use of negative indexes for the same purpose, like fruits[-1] .
We can explicitly calculate the last element index and then access it: fruits[fruits.length - 1] .
A bit cumbersome, isn’t it? We need to write the variable name twice.
Luckily, there’s a shorter syntax: fruits.at(-1) :
In other words, arr.at(i) :
- is exactly the same as arr[i] , if i >= 0 .
- for negative values of i , it steps back from the end of the array.
Methods pop/push, shift/unshift
A queue is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations:
- push appends an element to the end.
- shift get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st.
Arrays support both operations.
In practice we need it very often. For example, a queue of messages that need to be shown on-screen.
There’s another use case for arrays – the data structure named stack .
It supports two operations:
- push adds an element to the end.
- pop takes an element from the end.
So new elements are added or taken always from the “end”.
A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top:
For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out).
In computer science, the data structure that allows this, is called deque .
Methods that work with the end of the array:
Extracts the last element of the array and returns it:
Both fruits.pop() and fruits.at(-1) return the last element of the array, but fruits.pop() also modifies the array by removing it.
Append the element to the end of the array:
The call fruits.push(...) is equal to fruits[fruits.length] = ... .
Methods that work with the beginning of the array:
Extracts the first element of the array and returns it:
Add the element to the beginning of the array:
Methods push and unshift can add multiple elements at once:
An array is a special kind of object. The square brackets used to access a property arr actually come from the object syntax. That’s essentially the same as obj[key] , where arr is the object, while numbers are used as keys.
They extend objects providing special methods to work with ordered collections of data and also the length property. But at the core it’s still an object.
For instance, it is copied by reference:
…But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast.
But they all break if we quit working with an array as with an “ordered collection” and start working with it as if it were a regular object.
For instance, technically we can do this:
That’s possible, because arrays are objects at their base. We can add any properties to them.
But the engine will see that we’re working with the array as with a regular object. Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear.
The ways to misuse an array:
- Add a non-numeric property like arr.test = 5 .
- Make holes, like: add arr and then arr (and nothing between them).
- Fill the array in the reverse order, like arr , arr and so on.
Methods push/pop run fast, while shift/unshift are slow.
Why is it faster to work with the end of an array than with its beginning? Let’s see what happens during the execution:
It’s not enough to take and remove the element with the index 0 . Other elements need to be renumbered as well.
The shift operation must do 3 things:
- Remove the element with the index 0 .
- Move all elements to the left, renumber them from the index 1 to 0 , from 2 to 1 and so on.
- Update the length property.
The more elements in the array, the more time to move them, more in-memory operations.
The similar thing happens with unshift : to add an element to the beginning of the array, we need first to move existing elements to the right, increasing their indexes.
And what’s with push/pop ? They do not need to move anything. To extract an element from the end, the pop method cleans the index and shortens length .
The actions for the pop operation:
The pop method does not need to move anything, because other elements keep their indexes. That’s why it’s blazingly fast.
The similar thing with the push method.
One of the oldest ways to cycle array items is the for loop over indexes:
But for arrays there is another form of loop, for..of :
The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.
Technically, because arrays are objects, it is also possible to use for..in :
But that’s actually a bad idea. There are potential problems with it:
The loop for..in iterates over all properties , not only the numeric ones.
There are so-called “array-like” objects in the browser and in other environments, that look like arrays . That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.
The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.
Generally, we shouldn’t use for..in for arrays.
A word about “length”
The length property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one.
For instance, a single element with a large index gives a big length:
Note that we usually don’t use arrays like that.
Another interesting thing about the length property is that it’s writable.
If we increase it manually, nothing interesting happens. But if we decrease it, the array is truncated. The process is irreversible, here’s the example:
So, the simplest way to clear the array is: arr.length = 0; .
There is one more syntax to create an array:
It’s rarely used, because square brackets  are shorter. Also, there’s a tricky feature with it.
If new Array is called with a single argument which is a number, then it creates an array without items, but with the given length .
Let’s see how one can shoot themselves in the foot:
To avoid such surprises, we usually use square brackets, unless we really know what we’re doing.
Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:
Arrays have their own implementation of toString method that returns a comma-separated list of elements.
Also, let’s try this:
Arrays do not have Symbol.toPrimitive , neither a viable valueOf , they implement only toString conversion, so here  becomes an empty string,  becomes "1" and [1,2] becomes "1,2" .
When the binary plus "+" operator adds something to a string, it converts it to a string as well, so the next step looks like this:
Don’t compare arrays with ==
This operator has no special treatment for arrays, it works with them as with any objects.
Let’s recall the rules:
- Two objects are equal == only if they’re references to the same object.
- If one of the arguments of == is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter Object to primitive conversion .
- …With an exception of null and undefined that equal == each other and nothing else.
The strict comparison === is even simpler, as it doesn’t convert types.
So, if we compare arrays with == , they are never the same, unless we compare two variables that reference exactly the same array.
These arrays are technically different objects. So they aren’t equal. The == operator doesn’t do item-by-item comparison.
Comparison with primitives may give seemingly strange results as well:
Here, in both cases, we compare a primitive with an array object. So the array  gets converted to primitive for the purpose of comparison and becomes an empty string '' .
Then the comparison process goes on with the primitives, as described in the chapter Type Conversions :
So, how to compare arrays?
That’s simple: don’t use the == operator. Instead, compare them item-by-item in a loop or using iteration methods explained in the next chapter.
Array is a special kind of object, suited to storing and managing ordered data items.
The call to new Array(number) creates an array with the given length, but without elements.
- The length property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods.
- If we shorten length manually, the array is truncated.
Getting the elements:
- we can get element by its index, like arr
- also we can use at(i) method that allows negative indexes. For negative values of i , it steps back from the end of the array. If i >= 0 , it works same as arr[i] .
We can use an array as a deque with the following operations:
- push(...items) adds items to the end.
- pop() removes the element from the end and returns it.
- shift() removes the element from the beginning and returns it.
- unshift(...items) adds items to the beginning.
To loop over the elements of the array:
- for (let i=0; i<arr.length; i++) – works fastest, old-browser-compatible.
- for (let item of arr) – the modern syntax for items only,
- for (let i in arr) – never use.
To compare arrays, don’t use the == operator (as well as > , < and others), as they have no special treatment for arrays. They handle them as any objects, and it’s not what we usually want.
Instead you can use for..of loop to compare arrays item-by-item.
We will continue with arrays and study more methods to add, remove, extract elements and sort arrays in the next chapter Array methods .
Is array copied?
What is this code going to show?
The result is 4 :
That’s because arrays are objects. So both shoppingCart and fruits are the references to the same array.
Let’s try 5 array operations.
- Create an array styles with items “Jazz” and “Blues”.
- Append “Rock-n-Roll” to the end.
- Replace the value in the middle with “Classics”. Your code for finding the middle value should work for any arrays with odd length.
- Strip off the first value of the array and show it.
- Prepend Rap and Reggae to the array.
The array in the process:
Calling in an array context
What is the result? Why?
The call arr() is syntactically the good old obj[method]() , in the role of obj we have arr , and in the role of method we have 2 .
So we have a call of the function arr as an object method. Naturally, it receives this referencing the object arr and outputs the array:
The array has 3 values: initially it had two, plus the function.
Sum input numbers
Write the function sumInput() that:
- Asks the user for values using prompt and stores the values in the array.
- Finishes asking when the user enters a non-numeric value, an empty string, or presses “Cancel”.
- Calculates and returns the sum of array items.
P.S. A zero 0 is a valid number, please don’t stop the input on zero.
Run the demo
Please note the subtle, but important detail of the solution. We don’t convert value to number instantly after prompt , because after value = +value we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead.
A maximal subarray
The input is an array of numbers, e.g. arr = [1, -2, 3, 4, -9, 6] .
The task is: find the contiguous subarray of arr with the maximal sum of items.
Write the function getMaxSubSum(arr) that will return that sum.
If all items are negative, it means that we take none (the subarray is empty), so the sum is zero:
Please try to think of a fast solution: O(n 2 ) or even O(n) if you can.
Open a sandbox with tests.
We can calculate all possible subsums.
The simplest way is to take every element and calculate sums of all subarrays starting from it.
For instance, for [-1, 2, 3, -9, 11] :
The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.
The solution has a time complexity of O(n 2 ) . In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.
For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness.
Let’s walk the array and keep the current partial sum of elements in the variable s . If s becomes negative at some point, then assign s=0 . The maximum of all such s will be the answer.
If the description is too vague, please see the code, it’s short enough:
The algorithm requires exactly 1 array pass, so the time complexity is O(n).
You can find more detailed information about the algorithm here: Maximum subarray problem . If it’s still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that’s better than any words.
Open the solution with tests in a sandbox.
- If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
- If you can't understand something in the article – please elaborate.
- To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)
- © 2007—2024 Ilya Kantor
- about the project
- terms of usage
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
This chapter introduces collections of data which are ordered by an index value. This includes arrays and array-like constructs such as Array objects and TypedArray objects.
An array is an ordered list of values that you refer to with a name and an index.
For example, consider an array called emp , which contains employees' names indexed by their numerical employee number. So emp would be employee number zero, emp employee number one, and so on.
We will be focusing on arrays in this article, but many of the same concepts apply to typed arrays as well, since arrays and typed arrays share many similar methods. For more information on typed arrays, see the typed array guide .
Creating an array
The following statements create equivalent arrays:
element0, element1, …, elementN is a list of values for the array's elements. When these values are specified, the array is initialized with them as the array's elements. The array's length property is set to the number of arguments.
The bracket syntax is called an "array literal" or "array initializer." It's shorter than other forms of array creation, and so is generally preferred. See Array literals for details.
To create an array with non-zero length, but without any items, either of the following can be used:
Note: In the above code, arrayLength must be a Number . Otherwise, an array with a single element (the provided value) will be created. Calling arr.length will return arrayLength , but the array doesn't contain any elements. A for...in loop will not find any property on the array.
In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object:
If you wish to initialize an array with a single element, and the element happens to be a Number , you must use the bracket syntax. When a single Number value is passed to the Array() constructor or function, it is interpreted as an arrayLength , not as a single element.
This creates an array with only one element: the number 42.
This creates an array with no elements and arr.length set to 42.
This is equivalent to:
Calling Array(N) results in a RangeError , if N is a non-whole number whose fractional portion is non-zero. The following example illustrates this behavior.
If your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. Alternatively, create an empty array first before adding the single element to it.
You can also use the Array.of static method to create arrays with single element.
Referring to array elements
Because elements are also properties, you can access them using property accessors . Suppose you define the following array:
You can refer to the first element of the array as myArray , the second element of the array as myArray , etc… The index of the elements begins with zero.
Note: You can also use property accessors to access other properties of the array, like with an object.
Populating an array
You can populate an array by assigning values to its elements. For example:
Note: If you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.
You can also populate an array when you create it:
The length property is special. Its value is always a positive integer greater than the index of the last element if one exists. (In the example below, 'Dusty' is indexed at 30 , so cats.length returns 30 + 1 ).
You can also assign to the length property.
Writing a value that is shorter than the number of stored items truncates the array. Writing 0 empties it entirely:
Iterating over arrays
A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:
If you know that none of the elements in your array evaluate to false in a boolean context—if your array consists only of DOM nodes, for example—you can use a more efficient idiom:
This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience.
The forEach() method provides another way of iterating over an array:
The function passed to forEach is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a forEach loop.
Note that the elements of an array that are omitted when the array is defined are not listed when iterating by forEach , but are listed when undefined has been manually assigned to the element:
The Array object has the following methods:
The concat() method joins two or more arrays and returns a new array.
The join() method joins all elements of an array into a string.
The push() method adds one or more elements to the end of an array and returns the resulting length of the array.
The pop() method removes the last element from an array and returns that element.
The shift() method removes the first element from an array and returns that element.
The unshift() method adds one or more elements to the front of an array and returns the new length of the array.
The slice() method extracts a section of an array and returns a new array.
The at() method returns the element at the specified index in the array, or undefined if the index is out of range. It's notably used for negative indices that access elements from the end of the array.
The splice() method removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
The reverse() method transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.
The flat() method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
The sort() method sorts the elements of an array in place, and returns a reference to the array.
sort() can also take a callback function to determine how array elements are compared. The callback function is called with two arguments, which are two values from the array. The function compares these two values and returns a positive number, negative number, or zero, indicating the order of the two values. For instance, the following will sort the array by the last letter of a string:
- if a is less than b by the sorting system, return -1 (or any negative number)
- if a is greater than b by the sorting system, return 1 (or any positive number)
- if a and b are considered equivalent, return 0 .
The indexOf() method searches the array for searchElement and returns the index of the first match.
The lastIndexOf() method works like indexOf , but starts at the end and searches backwards.
The forEach() method executes callback on every array item and returns undefined .
The forEach method (and others below) that take a callback are known as iterative methods , because they iterate over the entire array in some fashion. Each one takes an optional second argument called thisArg . If provided, thisArg becomes the value of the this keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, this will refer to the global object ( window , globalThis , etc.) when the function is not strict , or undefined when the function is strict.
Note: The sort() method introduced above is not an iterative method, because its callback function is only used for comparison and may not be called in any particular order based on element order. sort() does not accept the thisArg parameter either.
The map() method returns a new array of the return value from executing callback on every array item.
The flatMap() method runs map() followed by a flat() of depth 1.
The filter() method returns a new array containing the items for which callback returned true .
The find() method returns the first item for which callback returned true .
The findLast() method returns the last item for which callback returned true .
The findIndex() method returns the index of the first item for which callback returned true .
The findLastIndex() method returns the index of the last item for which callback returned true .
The every() method returns true if callback returns true for every item in the array.
The some() method returns true if callback returns true for at least one item in the array.
The reduce() method applies callback(accumulator, currentValue, currentIndex, array) for each value in the array for the purpose of reducing the list of items down to a single value. The reduce function returns the final value returned by callback function.
If initialValue is specified, then callback is called with initialValue as the first parameter value and the value of the first item in the array as the second parameter value.
If initialValue is not specified, then callback 's first two parameter values will be the first and second elements of the array. On every subsequent call, the first parameter's value will be whatever callback returned on the previous call, and the second parameter's value will be the next value in the array.
If callback needs access to the index of the item being processed, or access to the entire array, they are available as optional parameters.
The reduceRight() method works like reduce() , but starts with the last element.
reduce and reduceRight are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.
You can transform back and forth between arrays and other data structures.
Grouping the elements of an array
The Object.groupBy() method can be used to group the elements of an array, using a test function that returns a string indicating the group of the current element.
Here we have a simple inventory array that contains "food" objects that have a name and a type .
To use Object.groupBy() , you supply a callback function that is called with the current element, and optionally the current index and array, and returns a string indicating the group of the element.
The code below uses an arrow function to return the type of each array element (this uses object destructuring syntax for function arguments to unpack the type element from the passed object). The result is an object that has properties named after the unique strings returned by the callback. Each property is assigned an array containing the elements in the group.
Note that the returned object references the same elements as the original array (not deep copies ). Changing the internal structure of these elements will be reflected in both the original array and the returned object.
If you can't use a string as the key, for example, if the information to group is associated with an object that might change, then you can instead use Map.groupBy() . This is very similar to Object.groupBy() except that it groups the elements of the array into a Map that can use an arbitrary value ( object or primitive ) as a key.
Arrays can contain "empty slots", which are not the same as slots filled with the value undefined . Empty slots can be created in one of the following ways:
In some operations, empty slots behave as if they are filled with undefined .
But in others (most notably array iteration methods), empty slots are skipped.
For a complete list of how array methods behave with sparse arrays, see the Array reference page .
The following code creates a two-dimensional array.
This example creates an array with the following rows:
Using arrays to store other properties
Arrays can also be used like objects, to store related information.
For example, when an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of RegExp.prototype.exec() , String.prototype.match() , and String.prototype.split() . For information on using arrays with regular expressions, see Regular Expressions .
Working with array-like objects
Array methods cannot be called directly on array-like objects.
But you can call them indirectly using Function.prototype.call() .
Array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays: