To help programmers manipulate and assign multiple values to a variable, the developer has provided users with a special type of variable, which is Array. The declaration through the array helps to shorten the time to access the elements in the variable, save memory … For an overview, we will go to learn Javascript Arrays.
What is JS Array?
Arrays are a special data type. These are variables that can hold one or more values in it. In Javascript, you can declare multiple data types in an array such as a string, object, number, or even another array.
An example of an array:
const cars = ["Saab", "Volvo", "BMW"]; console.log(cars);
Output:
Saab,Volvo,BMW
The use of arrays brings many conveniences to the programmer. In case your data is too much and the level of the data is equal, assuming the data members are in the class, declaring all the data into a variable as array will help the programmer to keep track and easier to manage.
Declare arrays in JS
There are two common ways to declare arrays. That is: use the [ ] character or use the new Array() syntax.
1. Declare arrays with [] character
Syntax:
var = [element0, element1, element2,… elementN];
Example declaration of array mixedArray includes the values: 1, two, three, 4 with [ ]:
var mixedArray = [1, "two", "three", 4];
2. Declare array with new Array()
Syntax:
var arr = new Array(value1, value2, …, valuen);
With:
- arr: Name of array
- Value1, Value2..: The value to be declared in the array.
For example:
var arr = new Array(1, 2, 4, 5, 9, 6);
The values of the variable are separated by commas, the values of the array variable will not require the same data type.
Accessing Array Elements jn JS
When processing data, it is inevitable to get an element. In the Javascript array, each value is considered as an element of the array, it will be sorted according to the programmer’s intention and assigned a number starting from 0. This is called an index. Thus, when you want to access an element in the array, you are getting the value by index.
Syntax:
arr[index];
With index are numbers starting from 0.
For example, you want to access the third value in an array of three elements: Saab,Volvo,BMW
Input:
const cars = ["Saab", "Volvo", "BMW"]; let car = cars[2]; console.log(car);
Output:
BMW
The length of the array
Length is an array-specific property. Programmers use the length property to know the length of an array in JS.
Syntax:
arr.length;
For instance:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.length; // 4
Browse elements in an array
Use a loop to iterate through the elements of an array. Usually, the for loop is most used when iterating arrays because of its explicitness.
For example:
var strArr = new Array("one", "two", "three", "four"); for (var i = 0; i < strArr.length; i++) { console.log(strArr[i]); }
Output:
one
two
three
four
Adding an element to the array
If you want to add a value to the end of the array, Js provides the push() function to do this. For example:
const fruits = ["Banana", "Orange", "Apple"]; fruits.push("Lemon"); // Banana, Orange, Apple, Lemon
If you want to add values to the beginning of the array, we have unshift() function. For example:
var colors = ["Red", "Yellow", "Blue"]; colors.unshift("Black"); console.log(colors); // Black, Red, Yellow, Blue
Delete an element of an array
Javascript provides a built-in function pop() so that programmers can remove the last element from an array if they want.
Code sample:
var colors = ["Red", "Yellow", "Blue"]; var last = colors.pop(); console.log(last); // Blue
Alternatively, if you want to remove the first element in the array, use the Shift() function.
Code sample:
var colors = ["Red", "Yellow", "Blue"]; var first = colors.shift(); console.log(first); // Red
Get a group of elements in an array
In some situations, the programmer only wants to get a few elements in the array, Js provides the user with the slice() function.
Syntax:
Array.slice(startIndex, endIndex)
Parameter:
- startIndex: position of the first element you want to get
- endIndex: position of the last element you want to get. If you want to get to the end, you can leave this index blank.
Code sample:
var fruits = ["Apple", "Banana", "Orange", "Mango", "Grape"]; console.log(fruits.slice(2)); // Orange,Mango,Grape
Sorting Arrays in Js
Sort() is used when you want to sort the elements in an array in ascending or descending order. By default, the sort() method will sort the array in ascending alphabetical order. In case you want to “customize” the sort order, the sort() method also accepts a parameter as a callback to help you do this.
Syntax:
array.sort(function (a, b)).
In there: function (a, b) (optional) is the callback for you to customize the order of the elements in the array. Parameters a, b are a pair of elements in the array. Callback returns >= 0 then a and b will not swap places, returns < 0 then a and b will swap places.
Code sample:
let arr = ["Toyota", "Subaru", "BMW"]; arr.sort(); console.log(arr); // ["BMW", "Subaru", "Toyota"]
Merge two arrays in JS
Javascript provides users with a built-in concat() function that merges arrays together into a composite array of the above arrays. When using this function, the returned result is the element value in the array you requested. The original array will remain intact.
Syntax:
array1.concat(array2, array3, ..., arrayX).
With array2, array3, …, arrayX are the arrays you want to combine with array1.
Code sample:
var pets = ["Cat", "Dog", "Chicken"]; var wilds = ["Tiger", "Wolf", "Bear"]; // Create a new array from 2 given array var animals = pets.concat(wilds); console.log(animals); // Result: Cat,Dog,Chicken,Tiger,Wolf,Bear
Thus, we have introduced you to the basic and necessary knowledge when working with arrays in Javascript. Getting to know and practice the methods mentioned in the article will make it easier for you to manipulate arrays.
List of tutorials related to arrays
Below we have compiled a list of tutorials related to arrays that may be of interest to you:
- Convert an array of objects to a map in javascript
- Check if an array doesn’t include a value
- Add a Key/Value pair to all Objects in Array in JavaScript
- Count Occurrences of each Element in Array in JavaScript
- Remove Duplicates from an Array in JavaScript
- Check if a Value is NOT in an Array using JavaScript
- Remove Empty Strings from an Array in JavaScript
- Find the First Array Element matching a Condition in JS
- How to Empty an Array in JavaScript
- Create an array containing 1 to n numbers in javascript
- Remove the last 2 elements from an array in javascript
- Remove empty elements from an array in javascript
- Push an Object to an Array in JavaScript
- Change a value of an object in an array in javascript
- Add element to array at specific index in JavaScript
- Get the last element of an array in Javascript
- Convert an Array to a String in JavaScript
- How to convert Map Keys to an Array in JavaScript
- Remove the last element from an array
- Push multiple Values to an Array in JavaScript
- Get the Difference between Two Arrays in JavaScript
- How to convert a Set to an Array in JavaScript
- Convert a String to Array of Numbers in JavaScript
- Filter an Array with Multiple Conditions in JavaScript
- Add value to an array if that value does not exist
- Check if Array has all Elements of Another Array in JavaScript
- Convert a Map to an Array of Objects in JavaScript
- Count the duplicates in an array using JavaScript
- Get an Object’s Keys as Array in JavaScript
- Get Difference between two Arrays of Objects in JavaScript
- How to Convert an Array to a Set in JavaScript
- How to convert Map Values to an Array in JavaScript
- Check if String contains Substring from Array in JS
- Add Array of Values to an Existing Set in JavaScript
- Convert an array to an object using javascript
- Convert an array to json using javascript
- Create a zero filled Array In JavaScript
- Get array of values from array of objects in javascript
- Get the min/max elements of an array in javascript
- Remove object from an array by its value in javascript
- How To Remove the First 2 Elements from an Array using JavaScript
- Remove Element(s) From An Array In JavaScript
- How To Remove The First Element From An Array Using JavaScript
- Check If All Values In Array Are True Using JS
- How To Find The Index Of All Occurrences Of An Element In JavaScript Array
- How to get the length of an array in JavaScript
- Remove the first N elements from an Array using JavaScript
- Remove Undefined Values from an Array using JavaScript
- Check if an Array contains Duplicates in JavaScript
- Sort an Array of Booleans in JavaScript
- Fix “map() method returns undefined”
- Get the index of an Object in an Array in JavaScript
- Reverse an Array without Modifying the Original in JavaScript
- Sort an Array of strings ignoring the Case in JavaScript
- How to get the Union of Two Arrays in JavaScript
- Remove the First and Last Array Elements in JavaScript
- Get every Nth Element of Array in JavaScript
- Convert all Array Elements to Uppercase in JavaScript
- Sort an Array of Objects by Boolean property in JavaScript
- Sort an Array with NULL values coming last in JavaScript
- Check if Multiple Values exist in Array in JavaScript
- Filter an Array of Objects based on a property in JavaScript
- Make Array.indexOf() case insensitive in JavaScript
- Capitalize the First Letter of Each Word in JS Array
- Trim all Strings in an Array using JavaScript
- Get the Second to Last Element in Array in JavaScript
- Convert Array of Numbers to Array of Strings in JavaScript
- Prevent adding Duplicates to an Array in JavaScript
- Check if Array contains Empty Elements in JavaScript
- Check if a String is contained in an Array in JavaScript
- Convert Array to String without Commas in JavaScript
- Get an Object’s Values as Array in JavaScript
- Count the True values in an Array using JavaScript
- Create an Array if it Doesn’t Exist in JavaScript
- Remove Empty Objects from an Array in JavaScript
- Get the Intersection of two Arrays in JavaScript
- Set all Array Elements to a Specific Value in JavaScript
- Check if Array of Strings contains a Substring in JavaScript
- How to Append one Array to Another in JavaScript
- Sort an Array of Objects by Date property in JavaScript
- Convert Array to String with Spaces in JavaScript
- Get the First and Last Elements of an Array in JavaScript
- Sum a Property in an Array of Objects in JavaScript
- Remove the last N elements from an Array in JavaScript
- Check if an Array Index exists in JavaScript
- Increment the Values in an Array using JavaScript
- How to parse a JSON Array in JavaScript
- Update an Object’s Property in Array of Objects in JS
Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB