Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype

JavaScript Array

  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals

JavaScript Spread Operator

  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

  • JavaScript Array splice()
  • JavaScript Array shift()
  • JavaScript Array unshift()

JavaScript Multidimensional Array

  • JavaScript Array pop()
  • JavaScript Array slice()

An array is an object that can store multiple values at once.

In the above example, we created an array to record the age of five students.

Array of Five Elements

Why Use Arrays?

Arrays allow us to organize related data by grouping them within a single variable.

Suppose you want to store a list of fruits. Using only variables, this process might look like this:

Here, we've only listed a few fruits. But what if we need to store 100 fruits?

For such a case, the easiest solution is to store them in an array.

An array can store many values in a single variable, making it easy to access them by referring to the corresponding index number.

  • Create an Array

We can create an array by placing elements inside an array literal [] , separated by commas. For example,

  • numbers - Name of the array.
  • [10, 30, 40, 60, 80] - Elements of the array.

Here are a few examples of JavaScript arrays:

Note: Unlike many other programming languages, JavaScript allows us to create arrays with mixed data types.

  • Access Elements of an Array

Each element of an array is associated with a number called an index , which specifies its position inside the array.

Consider the following array:

Here is the indexing of each element:

Index of Array Elements

We can use an array index to access the elements of the array.

Code Description
Accesses the first element .
Accesses the second element .
Accesses the third element .
Accesses the fourth element .
Accesses the fifth element .

Let's look at an example.

Remember: Array indexes always start with 0 , not 1.

  • Add Element to an Array

We can add elements to an array using built-in methods like push() and unshift() .

1. Using the push() Method

The push() method adds an element at the end of the array.

2. Using the unshift() Method

The unshift() method adds an element at the beginning of the array.

To learn more, visit Array push() and Array unshift() .

  • Change the Elements of an Array

We can add or change elements by accessing the index value. For example,

Here, we changed the array element in index 1 (second element) from work to exercise .

  • Remove Elements From an Array

We can remove an element from any specified index of an array using the splice() method.

In this example, we removed the element at index 2 (the third element) using the splice() method.

Notice the following code:

Here, (2, 1) means that the splice() method deletes one element starting from index 2 .

Note: Suppose you want to remove the second, third, and fourth elements. You can use the following code to do so:

To learn more, visit JavaScript Array splice() .

  • Array Methods

JavaScript has various array methods to perform useful operations. Some commonly used array methods in JavaScript are:

Method Description
Joins two or more arrays and returns a result.
Converts an array to a string of (comma-separated) array values.
Searches an element of an array and returns its position (index).
Returns the first value of the array element that passes a given test.
Returns the first index of the array element that passes a given test.
Calls a function for each element.
Checks if an array contains a specified element.
Sorts the elements alphabetically in strings and ascending order in numbers.
Selects part of an array and returns it as a new array.
Removes or replaces existing elements and/or adds new elements.

To learn more, visit JavaScript Array Methods .

More on Javascript Array

You can also create an array using JavaScript's new keyword. For example,

Note : It's better to create an array using an array literal [] for greater readability and execution speed.

We can remove an element from an array using built-in methods like pop() and shift() .

1. Remove the last element using pop().

2. Remove the first element using shift().

To learn more, visit Array pop() and Array shift() .

We can find the length of an array using the length property. For example,

In JavaScript, arrays are a type of object. However,

  • Arrays use numbered indexes to access elements.
  • Objects use named indexes (keys) to access values.

Since arrays are objects, the array elements are stored by reference . Hence, when we assign an array to another variable, we are just pointing to the same array in memory.

So, changing one will change the other because they're essentially the same array. For example,

Here, we modified the copied array arr1 , which also modified the original array arr .

  • JavaScript forEach

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of JavaScript Array to the test! Can you solve the following challenge?

Write a function to calculate the sum of numbers in an array.

  • Return the sum of all numbers in the array arr .
  • For example, if arr[] = [10, 20, 30] , the expected output is 10 + 20 + 30 = 60 .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

JavaScript forEach()

JavaScript Set and WeakSet

Home » JavaScript Tutorial » JavaScript Arrays

JavaScript Arrays

Summary : in this tutorial, you’ll learn about JavaScript arrays and their basic operations.

Introduction to JavaScript arrays

In JavaScript, an array is an ordered list of values. Each value is called an element specified by an index :

A JavaScript array has the following characteristics:

  • First, an array can hold values of mixed types. For example, you can have an array that stores elements with the types number, string, boolean, and null.
  • Second, the size of an array is dynamic and auto-growing. In other words, you don’t need to specify the array size up front.

Creating JavaScript arrays

JavaScript provides you with two ways to create an array.  The first one is to use the Array constructor as follows:

The scores  array is empty, which does hold any elements.

If you know the number of elements that the array will hold, you can create an array with an initial size as shown in the following example:

To create an array and initialize it with some elements, you pass the elements as a comma-separated list into the Array() constructor.

For example, the following creates the scores array that has five elements (or numbers):

Note that if you use the Array() constructor to create an array and pass a number into it, you are creating an array with an initial size.

However, when you pass a value of another type like string into the Array() constructor, you create an array with an element of that value. For example:

JavaScript allows you to omit the new operator when you use the Array() constructor. For example, the following statement creates the  artists array.

In practice, you’ll rarely use the Array() constructor to create an array.

The more preferred way to create an array is to use the array literal notation:

The array literal form uses the square brackets [] to wrap a comma-separated list of elements.

The following example creates the colors array that holds string elements:

To create an empty array, you use square brackets without specifying any element like this:

Accessing JavaScript array elements

JavaScript arrays are zero-based indexed. In other words, the first element of an array starts at index 0, the second element starts at index 1, and so on.

To access an element in an array, you specify an index in the square brackets [] :

The following shows how to access the elements of the mountains array:

To change the value of an element, you assign that value to the element like this:

Getting the array size

Typically, the length property of an array returns the number of elements. The following example shows how to use the length property:

Basic operations on arrays

The following explains some basic operations on arrays. You’ll learn advanced operations such as map() , filter() , and reduce() in the next tutorials.

1) Adding an element to the end of an array

To add an element to the end of an array, you use the push() method:

2) Adding an element to the beginning of an array

To add an element to the beginning of an array, you use the unshift() method:

3) Removing an element from the end of an array

To remove an element from the end of an array, you use the pop() method:

4) Removing an element from the beginning of an array

To remove an element from the beginning of an array, you use the shift() method:

5) Finding an index of an element in the array

To find the index of an element, you use the indexOf() method:

6) Check if a value is an array

To check if a value is an array, you use Array.isArray() method:

  • In JavaScript, an array is an order list of values. Each value is called an element specified by an index.
  • An array can hold values of mixed types.
  • JavaScript arrays are dynamic, which means that they grow or shrink as needed.
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)
  • Overview: JavaScript first steps

In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.

Prerequisites: A basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective: To understand what arrays are and how to manipulate them in JavaScript.

What is an array?

Arrays are generally described as "list-like objects"; they are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do super useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom.

If we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. This would be much longer to write out, less efficient, and more error-prone. If we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? We'll return to this example later on in the article.

As in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console .

Creating arrays

Arrays consist of square brackets and items that are separated by commas.

  • Suppose we want to store a shopping list in an array. Paste the following code into the console: js const shopping = [ "bread" , "milk" , "cheese" , "hummus" , "noodles" ] ; console . log ( shopping ) ;
  • In the above example, each item is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays. We can also mix data types in a single array — we do not have to limit ourselves to storing only numbers in one array, and in another only strings. For example: js const sequence = [ 1 , 1 , 2 , 3 , 5 , 8 , 13 ] ; const random = [ "tree" , 795 , [ 0 , 1 , 2 ] ] ;
  • Before proceeding, create a few example arrays.

Finding the length of an array

You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. Try the following:

Accessing and modifying array items

Items in an array are numbered, starting from zero. This number is called the item's index . So the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index, in the same way that you accessed the letters in a string .

  • Enter the following into your console: js const shopping = [ "bread" , "milk" , "cheese" , "hummus" , "noodles" ] ; console . log ( shopping [ 0 ] ) ; // returns "bread"

Note: We've said it before, but just as a reminder — JavaScript starts indexing arrays at zero!

  • Note that an array inside an array is called a multidimensional array. You can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. For example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this: js const random = [ "tree" , 795 , [ 0 , 1 , 2 ] ] ; random [ 2 ] [ 2 ] ;
  • Try making some more modifications to your array examples before moving on. Play around a bit, and see what works and what doesn't.

Finding the index of items in an array

If you don't know the index of an item, you can use the indexOf() method. The indexOf() method takes an item as an argument and will either return the item's index or -1 if the item is not in the array:

Adding items

To add one or more items to the end of an array we can use push() . Note that you need to include one or more items that you want to add to the end of your array.

The new length of the array is returned when the method call completes. If you wanted to store the new array length in a variable, you could do something like this:

To add an item to the start of the array, use unshift() :

Removing items

To remove the last item from the array, use pop() .

The pop() method returns the item that was removed. To save that item in a new variable, you could do this:

To remove the first item from an array, use shift() :

If you know the index of an item, you can remove it from the array using splice() :

In this call to splice() , the first argument says where to start removing items, and the second argument says how many items should be removed. So you can remove more than one item:

Accessing every item

Very often you will want to access every item in the array. You can do this using the for...of statement:

Sometimes you will want to do the same thing to each item in an array, leaving you with an array containing the changed items. You can do this using map() . The code below takes an array of numbers and doubles each number:

We give a function to the map() , and map() calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array.

Sometimes you'll want to create a new array containing only the items in the original array that match some test. You can do that using filter() . The code below takes an array of strings and returns an array containing just the strings that are greater than 8 characters long:

Like map() , we give a function to the filter() method, and filter() calls this function for every item in the array, passing in the item. If the function returns true , then the item is added to a new array. Finally it returns the new array.

Converting between strings and arrays

Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the split() method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.

Note: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.

  • Let's play with this, to see how it works. First, create a string in your console: js const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle" ;
  • Now let's split it at each comma: js const cities = data . split ( "," ) ; cities ;
  • Finally, try finding the length of your new array, and retrieving some items from it: js cities . length ; cities [ 0 ] ; // the first item in the array cities [ 1 ] ; // the second item in the array cities [ cities . length - 1 ] ; // the last item in the array
  • You can also go the opposite way using the join() method. Try the following: js const commaSeparated = cities . join ( "," ) ; commaSeparated ;
  • Another way of converting an array to a string is to use the toString() method. toString() is arguably simpler than join() as it doesn't take a parameter, but more limiting. With join() you can specify different separators, whereas toString() always uses a comma. (Try running Step 4 with a different character than a comma.) js const dogNames = [ "Rocket" , "Flash" , "Bella" , "Slugger" ] ; dogNames . toString ( ) ; // Rocket,Flash,Bella,Slugger

Active learning: Printing those products

Let's return to the example we described earlier — printing out product names and prices on an invoice, then totaling the prices and printing them at the bottom. In the editable example below there are comments containing numbers — each of these marks a place where you have to add something to the code. They are as follows:

  • Below the // number 1 comment are a number of strings, each one containing a product name and price separated by a colon. We'd like you to turn this into an array and store it in an array called products .
  • Below the // number 2 comment, start a for...of() loop to go through every item in the products array.
  • Below the // number 3 comment we want you to write a line of code that splits the current array item ( name:price ) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the Useful string methods article for some help, or even better, look at the Converting between strings and arrays section of this article.
  • As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the first strings article .
  • There is a variable called total that is created and given a value of 0 at the top of the code. Inside the loop (below // number 4 ) we want you to add a line that adds the current item price to that total in each iteration of the loop, so that at the end of the code the correct total is printed onto the invoice. You might need an assignment operator to do this.
  • We want you to change the line just below // number 5 so that the itemText variable is made equal to "current item name — $current item price", for example "Shoes — $23.99" in each case, so the correct information for each item is printed on the invoice. This is just simple string concatenation, which should be familiar to you.
  • Finally, below the // number 6 comment, you'll need to add a } to mark the end of the for...of() loop.

Active learning: Top 5 searches

A good use for array methods like push() and pop() is when you are maintaining a record of currently active items in a web app. In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. As new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number.

In this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. The idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. When the number of terms goes over 5, the last term starts being deleted each time a new term is added to the top, so the 5 previous terms are always displayed.

Note: In a real search app, you'd probably be able to click the previous search terms to return to previous searches, and it would display actual search results! We are just keeping it simple for now.

To complete the app, we need you to:

  • Add a line below the // number 1 comment that adds the current value entered into the search input to the start of the array. This can be retrieved using searchInput.value .
  • Add a line below the // number 2 comment that removes the value currently at the end of the array.

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript Array Programming Examples

JavaScript array is used to store multiple elements in a single variable. It is often used when we want to store a list of elements and access them by a single variable. Unlike most languages where the array is a reference to the multiple variables, in JavaScript, an array is a single variable that stores multiple elements.

JavaScript-Array-Programming-Examples

Example 1: Here is the basic example of an array in javascript.

Example 2: In this example, we are using a new keyword.

All the JavaScript array-related articles into three sections based on their difficulty levels: Easy, Medium, and Hard. This organization aims to help learners gradually progress from basic to more complex concepts.

The Easy level includes articles that cover fundamental operations and straightforward tasks with JavaScript arrays.

  • Remove Elements from a JavaScript Array
  • How to Remove Duplicate Elements from JavaScript Array
  • How to Get All Unique Values (Remove Duplicates) in a JavaScript Array
  • How to Get a Value from a JSON Array in JavaScript
  • How to Replace an Item from an Array in JavaScript
  • JavaScript Program to Find Duplicate Elements in an Array
  • How to Select a Random Element from Array in JavaScript
  • Create an Array of Given Size in JavaScript
  • How to Append an Element in an Array in JavaScript
  • JavaScript Array Reference
  • JavaScript Remove the Last Item from an Array
  • Get the First and Last Item in an Array Using JavaScript
  • Reverse an Array in JavaScript
  • How to Empty an Array in JavaScript
  • How to Initialize an Array in JavaScript
  • JavaScript Program to Convert an Array into a String
  • How to Add Elements to the End of an Array in JavaScript
  • Check if an Element is Present in an Array Using JavaScript
  • JavaScript Program to Find the Largest Element in an Array
  • How to Get First N Number of Elements from an Array in JavaScript

The Medium level includes articles that delve deeper into working with JavaScript arrays, exploring more advanced operations and methods:

  • How to Modify an Object’s Property in an Array of Objects in JavaScript
  • Sort an Object Array by Date in JavaScript
  • Copy Array Items into Another Array in JavaScript
  • Count Occurrences of All Items in an Array in JavaScript
  • Convert an Array to an Object in JavaScript
  • How to Compare Two Arrays in JavaScript
  • How to Add an Object to an Array in JavaScript
  • How to Insert an Item into Array at Specific Index in JavaScript
  • Create a Comma Separated List from an Array in JavaScript
  • Find the Min/Max Element of an Array Using JavaScript
  • How to Clone an Array in JavaScript
  • How to Creating HTML List from JavaScript Array
  • Convert Comma Separated String to Array Using JavaScript
  • How to Convert Set to Array in JavaScript
  • How to Create Two Dimensional Array in JavaScript
  • How to Find the Sum of All Elements of a Given Array in JavaScript
  • How to Create an Array Containing 1 to N Numbers in JavaScript
  • Different Ways to Delete an Item from an Array Using JavaScript
  • Best Way to Find an Item in an Array in JavaScript
  • Add New Elements at the Beginning of an Array Using JavaScript
  • How to Loop Through an Array Containing Multiple Objects and Access Their Properties in JavaScript
  • Remove Array Element Based on Object Property in JavaScript
  • How to Move an Array Element from One Array Position to Another in JavaScript
  • How to Store an Array in LocalStorage
  • Remove Empty Elements from an Array in JavaScript
  • How to Convert Byte Array to String in JavaScript
  • How to Sort Numeric Array Using JavaScript
  • JavaScript Program to Find Index of an Object by Key and Value in an Array
  • JavaScript Program to Change the Value of an Array Elements
  • JavaScript Program to Find the Most Frequent Element in an Array
  • JavaScript Program to Find the Most Frequently Occurring Element in an Array
  • How to Use Map on an Array in Reverse Order with JavaScript
  • How to Get the Standard Deviation of an Array of Numbers Using JavaScript
  • JavaScript Program to Find the Missing Number in a Given Integer Array of 1 to 100
  • How to Remove Falsy Values from an Array in JavaScript
  • How to Remove Smallest and Largest Elements from an Array in JavaScript
  • JavaScript Program to Find the First Non-Repeated Element in an Array
  • JavaScript Program to Find the Majority Element of an Array
  • JavaScript Get All Non-Unique Values from an Array
  • JavaScript Program to Find the Minimum Index of a Repeating Element in an Array

The Hard level includes articles that cover more intricate and less common tasks

  • How to Remove Duplicates from an Array of Objects Using JavaScript
  • How to Get Distinct Values from an Array of Objects in JavaScript
  • How to Convert an Object into Array of Objects in JavaScript
  • How to Convert an Array of Objects to a Map in JavaScript
  • Split an Array into Chunks in JavaScript
  • Check an Array of Strings Contains a Substring in JavaScript
  • How to Remove Multiple Elements from Array in JavaScript
  • JavaScript Program to Find Second Largest Element in an Array
  • How to Convert Map Keys to an Array in JavaScript
  • How to Group Objects in an Array Based on a Common Property into an Array of Arrays in JavaScript
  • JavaScript Program to Sort Words in Alphabetical Order
  • JavaScript Program for Quick Sort
  • How to Check a Value Exist at Certain Array Index in JavaScript
  • How to Get a List of Associative Array Keys in JavaScript
  • JavaScript Program to Find Index of First Occurrence of Target Element in Sorted Array
  • JavaScript Program to Merge Two Arrays Without Creating a New Array
  • JavaScript Program to Determine the Length of an Array
  • How to Remove Null Objects from Nested Array of Objects in JavaScript
  • JavaScript Program to Sort an Associative Array by Its Values
  • JavaScript Program to Find Next Smaller Element
  • JavaScript Program to Sort an Array Which Contain 1 to N Values
  • JavaScript Program to Find the Largest Subarray with a Sum Divisible by K
  • JavaScript Program to Find K Most Occurrences in the Given Array
  • JavaScript Program to Count Unequal Element Pairs from the Given Array
  • Sparse Table Using JavaScript Array
  • JavaScript Program to Find the Rotation Count in Rotated Sorted Array
  • JavaScript Program to Construct an Array from Its Pair Sum Array
  • JavaScript Program to Find Union and Intersection of Two Unsorted Arrays
  • How Many Numbers in the Given Array Are Less or Equal to the Given Value Using the Percentile Formula
  • JavaScript Program to Find Median in a Stream of Integers (Running Integers Using Array)
  • Find the OR and AND of Array Elements Using JavaScript
  • JavaScript Program to Find Maximum Profit by Buying and Selling a Share at Most Twice Using Array
  • JavaScript Program for K-th Largest Sum Contiguous Subarray
  • JavaScript Program to Find Maximum Distance Between Two Occurrences of Same Element in Array
  • Finding Mean at Every Point in JavaScript Array
  • JavaScript Program to Search a Target Value in a Rotated Array
  • Range Sum Query Using Sparse Table in JavaScript Array
  • JavaScript Program to Rearrange an Array in Maximum Minimum Form Using Two Pointer Technique
  • Transpose a Two-Dimensional (2D) Array in JavaScript
  • JavaScript Program to Find the Longest Consecutive Sequence of Numbers in an Array
  • JavaScript Program to Sort an Array of Objects by Property Values
  • JavaScript Program for Merge Sort
  • Square Root (Sqrt) Decomposition Algorithm Using JavaScript Array
  • Rearrange Array Such That Even Positioned Are Greater Than Odd in JavaScript
  • JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words
  • How to Filter an Array of Objects in ES6
  • How to Compare Two JavaScript Array Objects Using jQuery/JavaScript
  • How to Find Property Values in an Array of Object Using If-Else Condition in JavaScript
  • Create Array of Integers Between Two Numbers Inclusive in JavaScript/jQuery
  • How to Find the Nth Smallest/Largest Element from an Unsorted Array
  • How to Store All Dates in an Array Present in Between Given Two Dates in JavaScript
  • JavaScript Program to Sort an Array Using JavaScript When Array Elements Has Different Data Types
  • How to Count Number of Data Types in an Array in JavaScript
  • How to Find Every Element That Exists in Any of Two Given Arrays Once Using JavaScript
  • JavaScript Program to Find the Minimum Number of Swaps to Sort Array
  • JavaScript Program to Merge Two Sorted Arrays into a Single Sorted Array
  • JavaScript Program to Reorder an Array According to Given Indexes
  • JavaScript Program for Left Rotate by One in an Array
  • JavaScript Program to Create an Array of Unique Values from Multiple Arrays Using Set Object
  • How to Use Arrays to Swap Variables in JavaScript
  • JavaScript Program to Swap First and Last Elements in an Array
  • JavaScript Program to Split Map Keys and Values into Separate Arrays
  • JavaScript Program to Find the K-th Largest Sum Contiguous Subarray
  • JavaScript Program to Check if K-th Index Elements Are Unique
  • How to Create an Array Using Intersection of Two Arrays in JavaScript
  • JavaScript Program to Create an Array with a Specific Length and Pre-Filled Values
  • How to Remove Objects from Associative Array in JavaScript
  • How to Create an Array of Elements Ungrouping the Elements in an Array Produced by Zip in JavaScript
  • How to Use Loop Through an Array in JavaScript
  • JavaScript Program to Find Largest Three Elements in an Array
  • JavaScript Program to Find the Nth Smallest/Largest Element from an Unsorted Array
  • How to Convert CSV String File to a 2D Array of Objects Using JavaScript
  • Short Circuit Array forEach Like Calling Break
  • JavaScript Program for Space Optimization Using Bit Manipulations
  • How to Compute Union of JavaScript Arrays

We have a complete list of Javascript Array functions, to check those please go through this JavaScript Array Complete Reference article.

We have created an article of JavaScript Examples, and added list of questions based on Array, Object, Function, …, etc. Please visit this JavaScript Examples to get complete questions based articles list of JavaScript.

We have created a complete JavaScript Tutorial to help both beginners and experienced professionals. Please check this JavaScript Tutorial to get the complete content from basic syntax and data types to advanced topics such as object-oriented programming and DOM manipulation.

Recent articles on JavaScript

Please login to comment..., similar reads.

  • Web Technologies
  • javascript-array
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 10 Best Free VPN Services in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Shift Assignment Operators

Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

The = Operator

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

How to Manipulate Arrays in JavaScript

freeCodeCamp

By Bolaji Ayodeji

An important part of any programming language. Most times we need to do several operations on arrays, hence this article.

In this article, I would show you various methods of manipulating arrays in JavaScript [^^]

What are Arrays in JavaScript?

Before we proceed, you need to understand what arrays really mean.

In JavaScript, an array is a variable that is used to store different data types. It basically stores different elements in one box and can be later assesssed with the variable.

Declaring an array:

Arrays can contain multiple data types

Arrays can be manipulated by using several actions known as methods. Some of these methods allow us to add, remove, modify and do lots more to arrays.

I would be showing you a few in this article, let’s roll :)

NB: I used Arrow functions in this post, If you don’t know what this means, you should read here . Arrow function is an ES6 feature .

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

The JavaScript join() method combines all array elements into a string.

It is similar to toString() method, but here you can specify the separator instead of the default comma.

This method combines two arrays together or add more items to an array and then return a new array.

This method adds items to the end of an array and changes the original array.

This method removes the last item of an array and returns it.

This method removes the first item of an array and returns it.

This method adds an item(s) to the beginning of an array and changes the original array.

You can also add multiple items at once

This method changes an array, by adding, removing and inserting elements.

The syntax is:

  • **Index** here is the starting point for removing elements in the array
  • **deleteCount** is the number of elements to be deleted from that index
  • **element1, …, elementN** is the element(s) to be added

Removing items

after running splice() , it returns the array with the item(s) removed and removes it from the original array.
NB : The deleteCount does not include the last index in range.

If the second parameter is not declared, every element starting from the given index will be removed from the array:

In the next example we will remove 3 elements from the array and replace them with more items:

Adding items

To add items, we need to set the deleteCount to zero

This method is similar to splice() but very different. It returns subarrays instead of substrings.

This method copies a given part of an array and returns that copied part as a new array. It does not change the original array.

Here’s a basic example:

The best way to use slice() is to assign it to a new variable.

This method is used for strings . It divides a string into substrings and returns them as an array.

Here’s the syntax:string.split(separator, limit);

  • The **separator** here defines how to split a string either by a comma.
  • The **limit** determines the number of splits to be carried out

another example:

NB: If we declare an empty array, like this firstName.split(''); then each item in the string will be divided as substrings :

This method looks for an item in an array and returns the index where it was found else it returns -1

lastIndexOf()

This method works the same way indexOf() does except that it works from right to left. It returns the last index where the item was found

This method creates a new array if the items of an array pass a certain condition.

Checks users from Nigeria

This method creates a new array by manipulating the values in an array.

Displays usernames on a page. (Basic friend list display)

Image

This method is good for calculating totals.

reduce() is used to calculate a single value based on an array.

To loop through an array and sum all numbers in the array up, we can use the for of loop.

Here’s how to do same with reduce()

_If you omit the initial value, the total will by default start from the first item in the array._

The snippet below shows how the reduce() method works with all four arguments.

source: MDN Docs

Image

More insights into the reduce() method and various ways of using it can be found here and here .

This method is good for iterating through an array.

It applies a function on all items in an array

iteration can be done without passing the index argument

This method checks if all items in an array pass the specified condition and return true if passed, else false .

check if all numbers are positive

This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.

_c_hecks if at least one number is positive__

This method checks if an array contains a certain item. It is similar to .some() , but instead of looking for a specific condition to pass, it checks if the array contains a specific item.

If the item is not found, it returns false

There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs here for deeper insights.

  • toString() converts an array to a string separated by a comma.
  • join() combines all array elements into a string.
  • concat combines two arrays together or add more items to an array and then return a new array.
  • push() adds item(s) to the end of an array and changes the original array.
  • pop() removes the last item of an array and returns it
  • shift() removes the first item of an array and returns it
  • unshift() adds an item(s) to the beginning of an array and changes the original array.
  • splice() c hanges an array, by adding, removing and inserting elements.
  • slice() copies a given part of an array and returns that copied part as a new array. It does not change the original array.
  • split() divides a string into substrings and returns them as an array.
  • indexOf() looks for an item in an array and returns the index where it was found else it returns -1
  • lastIndexOf() looks for an item from right to left and returns the last index where the item was found.
  • filter() creates a new array if the items of an array pass a certain condition.
  • map() creates a new array by manipulating the values in an array.
  • reduce() calculates a single value based on an array.
  • forEach() iterates through an array, it applies a function on all items in an array
  • every() checks if all items in an array pass the specified condition and return true if passed, else false.
  • some() checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
  • includes() checks if an array contains a certain item.

Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.

Let's do a create a small function, one that converts a post title into a urlSlug.

URL slug is the exact address of a specific page or post on your site.

When you write an article on Freecodecamp News or any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.

Here’s a basic function that does that using some of the methods we learnt just now.

in postUrl , we convert the string to lowercase then we use the split() method to convert the string into substrings and returns it in an array

in post slug we join the returned array with a hyphen and then concatenate it to the category string and main url .

That’s it, pretty simple, right? :)

If you’re just getting started with JavaScript, you should check this repository here , I’m compiling a list of basic JavaScript snippets ranging from

  • Control flow

Don’t forget to Star and share! :)

PS: This article was first published on my blog here

Learn to code. Build projects. Earn certifications—All for free.

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

  • JavaScript Home
  • ▼JavaScript Exercises
  • Exercises Home
  • Fundamental(ES6) Part-I
  • Fundamental(ES6) Part-II
  • Error Handling
  • Conditional statements and loops
  • Event Handling
  • Asynchronous
  • Object-Oriented Programming
  • Linked List
  • String/Text
  • Bit Manipulation
  • Validation with Regular expression
  • Validation without Regular expression
  • Sorting Algorithm
  • Searching Algorithm
  • ..More to come..

JavaScript array - Exercises, Practice, Solution

Javascript array [53 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

1. Write a JavaScript function to check whether an `input` is an array or not. Test Data : console.log(is_array('w3resource')); console.log(is_array([1, 2, 4, 0])); false true Click me to see the solution

2. Write a JavaScript function to clone an array. Test Data : console.log(array_Clone([1, 2, 4, 0])); console.log(array_Clone([1, 2, [4, 0]])); [1, 2, 4, 0] [1, 2, [4, 0]] Click me to see the solution

3. Write a JavaScript function to get the first element of an array. Passing the parameter 'n' will return the first 'n' elements of the array. Test Data : console.log(first([7, 9, 0, -2])); console.log(first([],3)); console.log(first([7, 9, 0, -2],3)); console.log(first([7, 9, 0, -2],6)); console.log(first([7, 9, 0, -2],-3)); Expected Output : 7 [] [7, 9, 0] [7, 9, 0, -2] [] Click me to see the solution

4. Write a JavaScript function to get the last element of an array. Passing the parameter 'n' will return the last 'n' elements of the array. Test Data : console.log(last([7, 9, 0, -2])); console.log(last([7, 9, 0, -2],3)); console.log(last([7, 9, 0, -2],6)); Expected Output : -2 [9, 0, -2] [7, 9, 0, -2] Click me to see the solution

5. Write a simple JavaScript program to join all elements of the following array into a string. Sample array : myColor = ["Red", "Green", "White", "Black"]; Expected Output : "Red,Green,White,Black" "Red,Green,White,Black" "Red+Green+White+Black" Click me to see the solution

6. Write a JavaScript program that accepts a number as input and inserts dashes (-) between each even number. For example if you accept 025468 the output should be 0-254-6-8. Click me to see the solution

7. Write a JavaScript program to sort the items of an array. Sample array : var arr1 = [ -3, 8, 7, 6, 5, -4, 3, 2, 1 ]; Sample Output : -4,-3,1,2,3,5,6,7,8 Click me to see the solution 8. Write a JavaScript program to find the most frequent item in an array. Sample array : var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3]; Sample Output : a ( 5 times ) Click me to see the solution

9. Write a JavaScript program that accepts a string as input and swaps the case of each character. For example if you input 'The Quick Brown Fox' the output should be 'tHE qUICK bROWN fOX'. Click me to see the solution

10. Write a JavaScript program that prints the elements of the following array. Note : Use nested for loops. Sample array : var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]]; Sample Output : "row 0" " 1" " 2" " 1" " 24" "row 1" ------ ------ Click me to see the solution

11. Write a JavaScript program to find the sum of squares of a numerical vector. Click me to see the solution

12. Write a JavaScript program to compute the sum and product of an array of integers. Click me to see the solution

add elements in an blank array

14. Write a JavaScript program to remove duplicate items from an array (ignore case sensitivity). Click me to see the solution

15. We have the following arrays : color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "]; o = ["th","st","nd","rd"] Write a JavaScript program to display the colors in the following way : "1st choice is Blue ." "2nd choice is Green." "3rd choice is Red." - - - - - - - - - - - - - Note : Use ordinal numbers to tell their position. Click me to see the solution

16. Write a JavaScript program to find the leap years in a given range of years. Click me to see the solution

17. Write a JavaScript program to shuffle an array. Click me to see the solution

18. Write a JavaScript program to perform a binary search. Note : A binary search or half-interval search algorithm finds the position of a specified input value within an array sorted by key value. Sample array : var items = [1, 2, 3, 4, 5, 7, 8, 9]; Expected Output : console.log(binary_Search(items, 1)); //0 console.log(binary_Search(items, 5)); //4 Click me to see the solution

19. There are two arrays with individual values. Write a JavaScript program to compute the sum of each individual index value in the given array. Sample array : array1 = [1,0,2,3,4]; array2 = [3,5,6,7,8,13]; Expected Output : [4, 5, 8, 10, 12, 13] Click me to see the solution

20. Write a JavaScript program to find duplicate values in a JavaScript array. Click me to see the solution

21. Write a JavaScript program to flatten a nested (any depth) array. If you pass shallow, the array will only be flattened to a single level. Sample Data : console.log(flatten([1, [2], [3, [[4]]],[5,6]])); [1, 2, 3, 4, 5, 6] console.log(flatten([1, [2], [3, [[4]]],[5,6]], true)); [1, 2, 3, [[4]], 5, 6] Click me to see the solution

22. Write a JavaScript program to compute the union of two arrays. Sample Data : console.log(union([1, 2, 3], [100, 2, 1, 10])); [1, 2, 3, 10, 100] Click me to see the solution

23. Write a JavaScript function to find the difference between two arrays. Test Data : console.log(difference([1, 2, 3], [100, 2, 1, 10])); ["3", "10", "100"] console.log(difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]])); ["6"] console.log(difference([1, 2, 3], [100, 2, 1, 10])); ["3", "10", "100"] Click me to see the solution

24. Write a JavaScript function to remove. 'null', '0', '""', 'false', 'undefined' and 'NaN' values from an array. Sample array : [NaN, 0, 15, false, -22, '',undefined, 47, null] Expected result : [15, -22, 47] Click me to see the solution

25. Write a JavaScript function to sort the following array of objects by title value. Sample object :

Expected result :

Click me to see the solution

26. Write a JavaScript program to find a pair of elements (indices of the two numbers) in a given array whose sum equals a specific target number.

Input: numbers= [10,20,10,40,50,60,70], target=50 Output: 2, 3

27. Write a JavaScript function to retrieve the value of a given property from all elements in an array. Sample array : [NaN, 0, 15, false, -22, '',undefined, 47, null] Expected result : [15, -22, 47] Click me to see the solution

28. Write a JavaScript function to find the longest common starting substring in a set of strings.

Sample array : console.log(longest_common_starting_substring(['go', 'google'])); Expected result : "go"

29. Write a JavaScript function to fill an array with values (numeric, string with one character) within supplied bounds.

Test Data : console.log(num_string_range('a', "z", 2)); ["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"]

30. Write a JavaScript function that merges two arrays and removes all duplicate elements.

Test data : var array1 = [1, 2, 3]; var array2 = [2, 30, 1]; console.log(merge_array(array1, array2)); [3, 2, 30, 1]

31. Write a JavaScript function to remove a specific element from an array.

Test data : console.log(remove_array_element([2, 5, 9, 6], 5)); [2, 9, 6] Click me to see the solution

32. Write a JavaScript function to find an array containing a specific element.

Test data : arr = [2, 5, 9, 6]; console.log(contains(arr, 5)); [True] Click me to see the solution

33. Write a JavaScript script to empty an array while keeping the original.

Click me to see the solution .

34. Write a JavaScript function to get the nth largest element from an unsorted array.

Test Data : console.log(nthlargest([ 43, 56, 23, 89, 88, 90, 99, 652], 4)); 89

35. Write a JavaScript function to get random items from an array.

36. Write a JavaScript function to create a specified number of elements with a pre-filled numeric value array.

Test Data : console.log(array_filled(6, 0)); [0, 0, 0, 0, 0, 0] console.log(array_filled(4, 11)); [11, 11, 11, 11]

37. Write a JavaScript function to create a specified number of elements with a pre-filled string value array.

Test Data : console.log(array_filled(3, 'default value')); ["default value", "default value", "default value"] console.log(array_filled(4, 'password')); ["password", "password", "password", "password"] Click me to see the solution

38. Write a JavaScript function to move an array element from one position to another.

Test Data : console.log(move([10, 20, 30, 40, 50], 0, 2)); [20, 30, 10, 40, 50] console.log(move([10, 20, 30, 40, 50], -1, -2)); [10, 20, 30, 50, 40] Click me to see the solution

39. Write a JavaScript function to filter false, null, 0 and blank values from an array.

Test Data : console.log(filter_array_values([58, '', 'abcd', true, null, false, 0])); [58, "abcd", true] Click me to see the solution

40. Write a JavaScript function to generate an array of integer numbers, increasing one from the starting position, of a specified length.

Test Data : console.log(array_range(1, 4)); [1, 2, 3, 4] console.log(array_range(-6, 4)); [-6, -5, -4, -3] Click me to see the solution

41. Write a JavaScript function to generate an array between two integers of 1 step length.

Test Data : console.log(rangeBetwee(4, 7)); [4, 5, 6, 7] console.log(rangeBetwee(-4, 7)); [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] Click me to see the solution

42. Write a JavaScript function to find unique elements in two arrays.

Test Data : console.log(difference([1, 2, 3], [100, 2, 1, 10])); ["1", "2", "3", "10", "100"] console.log(difference([1, 2, 3, 4, 5], [1, [2], [3, [[4]]],[5,6]])); ["1", "2", "3", "4", "5", "6"] console.log(difference([1, 2, 3], [100, 2, 1, 10])); ["1", "2", "3", "10", "100"] Click me to see the solution

43. Write a JavaScript function to create an array of arrays, ungrouping the elements in an array produced by zip.

Test Data : unzip([['a', 1, true], ['b', 2, false]]) unzip([['a', 1, true], ['b', 2]]) Expected Output: [["a","b"],[1,2],[true,false]] [["a","b"],[1,2],[true]] Click me to see the solution

44. Write a JavaScript function to create an object from an array, using the specified key and excluding it from each value.

Test Data : indexOn([ { id: 10, name: 'apple' }, { id: 20, name: 'orange' } ], x => x.id) Expected Output: {"undefined":{"id":20,"name":"orange"}} Click me to see the solution

45. Write a JavaScript program to find all the unique values in a set of numbers.

Test Data : [1, 2, 2, 3, 4, 4, 5] [1, 2, 3, 4, 5] [1, -2, -2, 3, 4, -5, -6, -5] Expected Output: [1,2,3,4,5] [1,2,3,4,5] [1,-2,3,4,-5,-6] Click me to see the solution

46. Write a JavaScript program to generate all permutations of an array's elements (including duplicates).

Test Data : [1, 33, 5] [1, 3, 5, 7] [2, 4] Expected Output: [[1,33,5],[1,5,33],[33,1,5],[33,5,1],[5,1,33],[5,33,1]] [[1,3,5,7],[1,3,7,5],[1,5,3,7],[1,5,7,3],[1,7,3,5],[1,7,5,3],[3,1,5,7],[3,1,7,5],[3,5,1,7],[3,5,7,1],[3,7,1,5],[3,7,5,1],[5,1,3,7],[5,1,7,3],[5,3,1,7],[5,3,7,1],[5,7,1,3],[5,7,3,1],[7,1,3,5],[7,1,5,3],[7,3,1,5],[7,3,5,1],[7,5,1,3],[7,5,3,1]] [[2,4],[4,2]] Click me to see the solution

47. Write a JavaScript program to remove all false values from an object or array.

Test Data : const obj = { a: null, b: false, c: true, d: 0, e: 1, f: '', g: 'a', h: [null, false, '', true, 1, 'a'], i: { j: 0, k: false, l: 'a' } Expected Output: {"c":true,"e":1,"g":"a","h":[true,1,"a"],"i":{"l":"a"}} Click me to see the solution

48. Write a JavaScript program that takes an array of integers and returns false if every number is not prime. Otherwise, return true.

Test Data : ([2,3,5,7]) -> true ([2,3,5,7,8]) -> false Expected Output: Original array of integers: 2,3,5,7 In the said array check every numbers are prime or not! true Original array of integers: 2,3,5,7,8 In the said array check every numbers are prime or not! false Click me to see the solution

49. Write a JavaScript program that takes an array of numbers and returns the third smallest number.

Test Data : (2,3,5,7,1) -> 3 (2,3,0,5,7,8,-2,-4) -> 0 Expected Output: Original array of numbers: 2,3,5,7,1 Third smallest number of the said array of numbers: 3 Original array of numbers: 2,3,0,5,7,8,-2,-4 Third smallest number of the said array of numbers: 0 Click me to see the solution

50. Write a JavaScript program that takes an array with mixed data type and calculates the sum of all numbers.

Test Data : ([2, "11", 3, "a2", false, 5, 7, 1]) -> 18 ([2, 3, 0, 5, 7, 8, true, false]) -> 25 Expected Output: Original array: 2,11,3,a2,false,5,7,1 Sum all numbers of the said array: 18 Original array: 2,3,0,5,7,8,true,false Sum all numbers of the said array: 25 Click me to see the solution

51. Write a JavaScript program to check if an array is a factor chain or not.

A factor chain is an array in which the previous element is a factor of the next consecutive element. The following is a factor chain: [2, 4, 8, 16, 32] // 2 is a factor of 4 // 4 is a factor of 8 // 8 is a factor of 16 // 16 is a factor of 32

Test Data : ([2, 4, 8, 16, 32]) -> true ([2, 4, 16, 32, 64]) -> true ([2, 4, 16, 32, 68]) -> false Expected Output: Original array: Check the said array is a factor chain or not? true Original array: Check the said array is a factor chain or not? true Original array: Check the said array is a factor chain or not? false Click me to see the solution

52. Write a JavaScript program to get all the indexes where NaN is found in a given array of numbers and NaN.

Test Data : ([2, NaN, 8, 16, 32]) -> [1] ([2, 4, NaN, 16, 32, NaN]) -> [2,5] ([2, 4, 16, 32]) ->[] Expected Output: Original array: 2,NaN,8,16,32 Find all indexes of NaN of the said array: 1 Original array: 2,4,NaN,16,32,NaN Find all indexes of NaN of the said array: 2,5 Original array: 2,4,16,32 Find all indexes of NaN of the said array: Click me to see the solution

53. Write a JavaScript program to count the number of arrays inside a given array.

Test Data : ([2,8,[6],3,3,5,3,4,[5,4]]) -> 2 ([2,8,[6,3,3],[4],5,[3,4,[5,4]]]) -> 3 Expected Output: Number of arrays inside the said array: 2 Number of arrays inside the said array: 3 Click me to see the solution

More to Come !

* To run the code mouse over on Result panel and click on 'RERUN' button. *

See the Pen javascript-common-editor by w3resource ( @w3resource ) on CodePen .

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Javascript - Array Assignment

I am currently taking a course on Javascript at Khan Academy and Im having some trouble with one of the assignments. I have posted the question there, but I have noticed that there is less volunteers willing to help there, so I thought I`d ask here. I have an Assignment on JS Arrays ( https://www.khanacademy.org/computing/computer-programming/programming/arrays/p/project-make-it-rain ) with the following requirements:

To make an animation of rain, it's best if we use arrays to keep track of the drops and their different properties. Start with this simple code and build on it to make a cool rain animation. Here are some ideas for what you could do: Add more drops to the arrays. Make it so that the drops start back at the top once they've reached the bottom, using a conditional. Make an array of colors, so that every drop is a different color. Make other things rain, like snowflakes (using more shape commands) or avatars (using the image commands). Make it so that when the user clicks, a new drop is added to the array. Initialize the arrays using a for loop and random() function, at the beginning of the program.

Question 1)

I've got it to use a random colour when the raindrop is called, but it overwrites the previous drop's colour if you call it before the previous drop goes off screen. I've tried moving the fill function outside the loop, and around the loop to no avail. Can anyone give me some insight on this? What am I doing wrong?

Question 2)

I've got a conditional (if/else) to make the raindrop start back at the top, but it drops much slower the second time, and only repeats once. Having trouble figuring out the logic of why this is happening in order to "debug" it.

Current code:

digglemister's user avatar

You need to make a fill call for each raindrop that is drawn, per iteration of the for loop inside draw . For a raindrop to maintain its color as it falls (between draw calls) you need to store its color in an additional array, and initialize the corresponding color when you create new drops.

Simply reset the y value in the y array to make the drop start over. I'm not sure what the ellipse call was doing in your code - see below.

Catalyst's user avatar

  • Re: Q2) I tried setting the yPositions to 0 but it wasnt working for some reason. Might have been a syntax error.. ---------------------------- Amazing answer. One thing that Im noticing is if I click to push a new raindrop, it sets the original raindrops colour to a new value. Do I need to make a separate dropColor var for mouseClicked drops so they dont change existing drops –  Nathan Fleck Commented Jan 3, 2016 at 16:57
  • @NathanFleck I've updated the answer so that doesn't happen, I had the fill call after ellipse and it needed to be before. It was likely affecting other drops negatively as well. The number of fill calls and ellipse calls should be one to one. –  Catalyst Commented Jan 3, 2016 at 20:42

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript arrays or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Is there a way to prove ownership of church land?
  • Is this host and 'parasite' interaction feasible?
  • When has the SR-71 been used for civilian purposes?
  • I'm not quite sure I understand this daily puzzle on Lichess (9/6/24)
  • What is the translation of this quote by Plato?
  • How to truncate text in latex?
  • how do I fix apt-file? - not working and added extra repos
  • Investigate why packages are held back, and stop release upgrade
  • How to clean a female disconnect connector
  • Is "She played good" a grammatically correct sentence?
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • A seven letter *
  • How high does the ocean tide rise every 90 minutes due to the gravitational pull of the space station?
  • SOT 23-6 SMD marking code GC1MGR
  • Is there a non-semistable simple sheaf?
  • What is this movie aircraft?
  • Applying to faculty jobs in universities without a research group in your area
  • What was the first "Star Trek" style teleporter in SF?
  • Where is this railroad track as seen in Rocky II during the training montage?
  • Does a party have to wait 1d4 hours to start a Short Rest if no healing is available and an ally is only stabilized?
  • How to raise and lower indices as a physicist would handle it?
  • How does the phrase "a longe" meaning "from far away" make sense syntactically? Shouldn't it be "a longo"?
  • Do Ethernet Switches have MAC Addresses?
  • PCA to help select variables?

array assignment on javascript

COMMENTS

  1. JavaScript Arrays

    JavaScript Arrays

  2. Array

    JavaScript arrays are zero-indexed: the first element of an array is at index 0, ... Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, ...

  3. Destructuring assignment

    Destructuring assignment - JavaScript - MDN Web Docs

  4. The JavaScript Array Handbook

    Here is an example of an array with four elements: type Number, Boolean, String, and Object. const mixedTypedArray = [100, true, 'freeCodeCamp', {}]; The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.

  5. JavaScript Array (with Examples)

    JavaScript Array (with Examples)

  6. The Beginner's Guide to JavaScript Array with Examples

    JavaScript provides you with two ways to create an array. The first one is to use the Array constructor as follows: let scores = new Array (); Code language: JavaScript (javascript) The scores array is empty, which does hold any elements. If you know the number of elements that the array will hold, you can create an array with an initial size ...

  7. JavaScript Array Handbook

    How to Create Multi-dimensional Arrays; JavaScript Array Methods Cheat Sheet; Wrapping Up; How Arrays Work in JavaScript. In JavaScript, an array is implemented as an object that can have a group of items, elements, or values as an ordered collection. This means you can access an array's element using its position in the collection.

  8. Arrays

    Arrays. In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.

  9. JavaScript Array Tutorial

    In JavaScript, an array is an object constituted by a group of items having a specific order. Arrays can hold values of mixed data types and their size is not fixed. How to Create an Array in JavaScript. You can create an array using a literal syntax - specifying its content inside square brackets, with each item separated by a comma.

  10. Arrays

    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.

  11. Destructuring Assignment in JavaScript

    Destructuring Assignment in JavaScript. Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables. In Destructuring Assignment on the left-hand side, we define which ...

  12. JavaScript Destructuring

    Destructuring Assignment Syntax. The destructuring assignment syntax unpack object properties into variables: let {firstName, lastName} = person; It can also unpack arrays and any other iterables: let [firstName, lastName] = person;

  13. Destructuring assignment

    Destructuring assignment

  14. Array declaration & assignment (JavaScript)

    Javascript assigning multiple arrays. 1. Javascript: Array declaration - derived from textbook studies. 2. Javascript - Array Assignment. 2. Array as a Variable Assignment in Javascript. 0. Declaration of arrays. Hot Network Questions Function to find the most common numeric ordered pairings (value, count)

  15. JavaScript Arrays

    The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor function. This approach allows for dynamic initialization and can be used to create arrays with a specified length or elements. Syntax: let arrayName = new Array(); Example: javascript.

  16. JavaScript Array Programming Examples

    In JavaScript, slice() and splice() are array methods with distinct purposes. `slice()` creates a new array containing selected elements from the original, while `splice()` modifies the original array by adding, removing, or replacing elements. slice():The slice() method in JavaScript extracts a section of an array and returns a new array containin

  17. JavaScript Assignment

    JavaScript Assignment

  18. How to Manipulate Arrays in JavaScript

    Declaring an array: let myBox = []; // Initial Array declaration in JS. Arrays can contain multiple data types. let myBox = ['hello', 1, 2, 3, true, 'hi']; Arrays can be manipulated by using several actions known as methods. Some of these methods allow us to add, remove, modify and do lots more to arrays.

  19. javascript assignment operator array

    When your "test" function returns, you're correct that "names" is "gone". However, its value is not, because it's been assigned to a global variable. The value of the "names" local variable was a reference to an array object. That reference was copied into the global variable, so now that global variable also contains a reference to the array object.

  20. JavaScript array

    JavaScript array [53 exercises with solution] [An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a JavaScript function to check whether an `input` is an array or not. Test Data: console.log(is_array('w3resource')); console.log(is_array([1, 2, 4, 0])); false true Click me to see the ...

  21. Javascript

    Make an array of colors, so that every drop is a different color. Make other things rain, like snowflakes (using more shape commands) or avatars (using the image commands). Make it so that when the user clicks, a new drop is added to the array. Initialize the arrays using a for loop and random() function, at the beginning of the program.