JavaScript Arrays

JavaScript Arrays

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:

Leave a Reply

Your email address will not be published. Required fields are marked *