JavaScript Arrays

An array is a variable type holding several values. For example,

const computers = ["HP", "Lenovo", "IBM"];

What’s the Point of using an Array?

If you have a list of objects, for example, a list of computer names, you could store the computers in separate variables like this:

let computer1 = "HP";
let computer2 = "Lenovo";
let computer3 = "IBM";

But what if you want to search through all computers to find a specific one? What if you had 1000 or more computers instead of three? The answer is an array! Many values are stored in an array with a single name, and the values can be accessed by referring to an index number.

How to make an Array

The simplest approach to generate a JavaScript Array is to use an array literal. The syntax for creating an array is as follows:

const array_name = [item1, item2, …];

The const keyword used above is commonly used when declaring arrays. Also, the use of spaces and line breaks is unimportant. Multiple lines are used in a declaration:

const computers = [
  "HP",
  "Lenovo",
  "IBM"
];

You may also initialize an array and then provide the elements to it:

const computers = [];

computers[0]= "HP";
computers[1]= "Lenovo";
computers[2]= "IBM";

New is a JavaScript keyword used in a variety of ways. The following array is created, and values are assigned to it:

const computers = new Array("HP", "Lenovo", "IBM");

The two samples above are identical. It is not necessary to use a new Array (). Instead, you can use the literal array approach for simplicity, readability, and execution speed.

Accessing the Elements of an Array

The index number is used to access an array element:

const computers =["HP", "Lenovo", "IBM"];
let computer = computers[0];

The indexes of arrays begin with 0. The first element is [0]. The second element is [1.]

Changing the Value of an Array Element

In computers, this statement modifies the value of the first element:

computers[0] = "Dell";

const computers = ["HP", "Lenovo", "IBM"];
computers[0] = "Dell";

Get Full Access to the Array

The complete array can be retrieved in JavaScript by referring to the array name:

const computers = ["HP", "Lenovo", "IBM"];
console.log(computers);

Are Arrays Objects?

Arrays are a unique kind of object. For arrays, the typeof operation in JavaScript returns “object.” JavaScript arrays, on the other hand, are best described as arrays. Numbers are used to accessing the “elements” of arrays. person[0] returns Ann in this case:

const student = ["Ann", "Tom", 19];

To access its “members,” objects use names. student.firstName returns Ann in this case:

const student = {firstName:"Ann", lastName:"Tom", age:19};

Objects Can Be Used As Array Elements

Variables in JavaScript can be objects. Arrays are unique types of objects. As a result, you can have different variables in the same Array. An Array can contain items. An Array can contain functions. An array can contain arrays:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myComputers;

Array Methods and Properties

The built-in array attributes and functions of JavaScript arrays are their main strength. For instance,

computers.length // Returns the number of elements
computers.sort() // Sorts the array

The following section covers array methods.

The property’s length (length)

An array’s length property returns the array’s length (the number of array elements).

const computers = ["HP", "Lenovo", "IBM"];
let compLen = computers.length;

The length property consistently exceeds the highest array index by one.

Getting to the First Element of an Array

const computers = ["HP", "Lenovo", "IBM"];
let computer = computers[0];

Getting to the End of the Array

const computers = ["HP", "Lenovo", "IBM"];
let computer = computers[computers.length - 1];

Looping Elements in Array

A for loop is one approach to iterate through an array:

const computers = ["HP", "Lenovo", "IBM"];
let comp_len = computers.length;

for (let i = 0; i < comp_len; i++) {
console.log(computers[i] );
}

Alternatively, use the Array.forEach() function from the Array class:

const computers = ["HP", "Lenovo", "IBM"];

computers.forEach(myFunction);

function myFunction(value) {
console.log(value);
}

Adding Elements to an Array

The push() method is the simplest way to add a new element to an array:

const computers = ["HP", "Lenovo", "IBM"];
computers.push("Dell"); // Adds a new element (Dell) to computers

The arrays’ property length is used to add new elements to an array:

const computers = ["HP", "Lenovo", "IBM"];
computers[computers.length] = "Dell"; // Adds "Dell" to Computers

Adding elements with high indices to an array can result in undefined “holes”:

const computers = ["HP", "Lenovo", "IBM"];
computers[6] = "Dell"; // Creates undefined "holes" in computers

Associative Arrays

Associative Arrays are a type, and Several computer languages support arrays with named indexes. Associative arrays are arrays with named indexes or hashes. It is crucial to remember that JavaScript does not support named indexes in arrays. Arrays in JavaScript always have numbered indexes.

const student = [];
student[0] = "Ann";
student[1] = "Tom";
student[2] = 19;
student.length; // Will return 3
student[0]; // Will return "Ann"

WARNING!! Using named indexes will cause JavaScript to rename the array to an object. As a result, some array methods and properties will provide inaccurate results.

const student = [];
student["firstName"] = "Ann";
student["lastName"] = "Tom";
student["age"] = 19;
student.length; // Will return 0
student[0]; // Will return undefined

Arrays and Objects: What’s the Difference?

  • Arrays in JavaScript employ numbered indexes.
  • Objects in JavaScript employ named indexes.
  • Arrays are a type of object that has numbered indexes.

When Should You Use Arrays? When should you utilize objects?

JavaScript does not support associative arrays. Use objects in case you intend to have your element names as strings. Also, use arrays when you intend to use numbers as element names.

new Array() in JavaScript

new Array() is a built-in array constructor in JavaScript (). However, instead, you can safely use [].

Both of these statements produce a new empty array called scores:

const scores = new Array();
const scores = [];

Both of these statements produce a new array containing six numbers:

const scores = new Array(50, 9, 14, 21, 30);
const scores = [50, 9, 14, 21, 30];

A Common Mistake

const scores = [50];

The scores above are not the same as:

const scores = new Array(50);

// Create an array with one element:
const scores = [50];

// Create an array with 50 undefined elements:
const scores = new Array(50);

Because a JavaScript array is an object, the typeof operation returns an object. To address this issue, Array.isArray() is a new method in ECMAScript 5 put to use:

Array.isArray(computers);

Alternatively, if a particular constructor creates an object, the instanceof operator returns true:

const computers = ["HP", "Lenovo", "IBM"];

How to Identify an Array

It is not intuitive to tell if the variable you are using is an array. The issue is that the typeof operator in JavaScript returns “object”:

const computers = ["HP", "Lenovo", "IBM"];
let type = typeof computers;

Sorting Arrays in JavaScript

The sort() method alphabetically sorts an array:

const computers = ["HP", "Lenovo", "IBM"];
computers.sort();

How to Reverse an Array

The reverse() method is responsible for reversing an array’s elements. As a result, it sorts an array in a descending manner as shown:

const computers = ["HP", "Lenovo", "IBM"];
computers.sort();
computers.reverse();

Sorting by Numbers

The sort() function by default organizes data as strings. It is excellent for strings (“Apple” comes before “HP”). When arranging numbers as strings, however, “36” is more than “126” because “3” is more significant than “1.” Consequently, when numbers are being sorted, the sort() method returns an inaccurate result. You can counter this by using a comparison function:

const scores = [10,6,35, 95, 6, 30, 15];
scores.sort(function(x, y){return x – y});

You can also employ the same technique to sort an array in a descending manner.

const scores = [10,6,35, 95, 6, 30, 15];
scores.sort(function(x, y){return y – x});

The Function of Comparison

The comparison function’s goal puts forth a different sort order. The result of a comparison method should be positive, neutral(zero), or negative. However, this relies on the arguments provided.

function(x, y){return x - y}

The sort() function works by parsing the two values being evaluated to the comparison function whose outcome is either positive, zero, or negative. x is ranked first if the outcome is negative, followed by y. If the outcome is positive, y ranks first, then x. However, if the outcome is 0, then there are no changes to the sort order of the two values.

Example:

The compare function compares two values throughout the array (x, y). For instance, the sort() method compares between 6 and 126. The sort function sorts 6 as a number less than 126 since the function calculates 6 – 126 (x – y), and the outcome is negative (-120).

const scores = [10,6,35, 95, 6, 30, 15];

function arrayFunction1() {
console.log(scores.sort());
}

function arrayFunction2() {
scores.sort(function(x, y){return x - y});
console.log(scores);
}

Array Sorting in Random Order

const scores = [10,6,35, 95, 6, 30, 15];
scores.sort(function(x, y){return 0.5 - Math.random()});

The Yates Fisher Method

The array.sort() example above is not realistic; it favors some values over others. The Fisher-Yates shuffle is the most popular proper method, and it was used first in 1938 for data science purposes. It is converted into JavaScript as follows:

const scores = [10,6,35, 95, 6, 30, 15];

for (let i = scores.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * i)
let k =scores[i]
scores[i] = scores[j]
scores[j] = k
}

Find the Array Value with the Highest (or Lowest) Value

JavaScript has no built-in functions for evaluating the minimum or maximum value in a given array. The available workaround is to sort the array then use indexes to get both the lowest and highest values in the array.

Sorting in ascending order:

const scores = [10,6,35, 95, 6, 30, 15];
points.sort(function(x, y){return x - y});

On the other hand, you can sort descending as follows:

const scores = [10,6,35, 95, 6, 30, 15];
scores.sort(function(x, y){return y - x});

If you only want to elucidate the highest (or lowest) value, sorting an entire array is a highly wasteful way.

using Math.max()

To determine the greatest number in an array, use Math.max.apply:

function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
Math.max.apply(null, [21, 32, 53]) is equivalent to Math.max(21, 32, 53).

Using the Math.min() function

Use Math.min.apply to find out the smallest value in a given array.

  function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}

JavaScript Methods with Minimum and Maximum Values

Using a “home-built” is a quick fix. This function loops through the entire array, comparing each value to the highest one found:

Finding the Max

function findMaxValueInArray(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}

Finding the Min

function findMinValueInArray(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}

It works by making comparisons of every value in the loop to the specified smallest value found.

Sorting Arrays of Objects

Objects are frequently found in JavaScript arrays. The sort() method does not discriminate some data types and instead sorts all of them regardless of their properties.

Comparing property values in a comparison function:

computers.sort(function(x, y){return x.year - y.year});

Making comparisons on the properties of the string is tricky.

computers.sort(function(x, y){
let a = x.type.toLowerCase();
let b = y.type.toLowerCase();
if (a < b) {return -1;} if (a > b) {return 1;}
return 0;
});

Iterating an Array in JavaScript

Array iteration techniques iterate through all of the items in the array.

forEach in JavaScript ()

The forEach() method loops through every element in the array while calling the callback function.

const nums = [50, 9, 14, 21, 30];

nums.forEach(arrayFunction);

function arrayFunction(value, index, array) {
console.log(value);
}

Array map() in JavaScript

The map() method builds a new array by applying a function to individual elements in the array. Further, the map() method
does not run the function when the array items have no values. In addition, the map() procedure does not alter the
initial array.

Example showing every array element being multiplied by two:

const nums1 = [50, 9, 14, 21, 30];
const nums2 = nums1.map(arrayFunction);

function arrayFunction(value, index, array) {
return value * 2;
}

By default, the function needs three arguments. But if the only argument provided is the value, then both the array and index parameters are omitted from the callback function.

const nums1 = [50, 9, 14, 21, 30];
const nums2 = nums1.map(arrayFunction);

function arrayFunction(value) {
return value * 2;
}

Array filter() in JavaScript

Using the filter method in an array ensures that values in the array that meet specific criteria are returned. This example makes a new array out of components that have a value greater than 20:

const nums = [50, 9, 14, 21, 30];
const over_20 = nums.filter(arrayFunction);

function arrayFunction(value, index, array) {
return value > 20;
}

JavaScript Array reduce()

The reduce() method runs on individual array elements to generate a single value. It works from the left to the right
end of the given array. However, the process does not alter the initial array.

const nums = [50, 9, 14, 21, 30];
let sum = nums.reduce(myFunction);

function myFunction(total, value, index, array) {
return total + value;
}

In the following example, the reduce method is given an initial value.

const nums = [50, 9, 14, 21, 30];
let sum = nums.reduce(myFunction, 100);

function myFunction(total, value) {
return total + value;
}

JavaScript Array reduceRight ()

Similar to the reduce method, the reduceRight runs the function on every element in the array to produce a single value. On the contrary, it works from the right end to the left end of the array. It also fails to reduce the original array.

The example below demonstrates how to get the total value of all the items in the array.

const nums = [50, 9, 14, 21, 30];
let sum = nums.reduceRight(arrayFunction);

function arrayFunction(total, value, index, array) {
return total + value;
}

every () Array in JavaScript

The every() method examines every array value to see if they pass a test. This example determines whether all array values are greater than 20:

const nums = [50, 9, 14, 21, 30];
let allOver_20 = nums.every(arrayFunction);

function arrayFunction(value, index, array) {
return value > 20;
}

An array of JavaScript some()

The some() method seeks to determine if a set of array values pass a test or not. This example determines whether or not some array values are greater than 20:

const nums = [50, 9, 14, 21, 30];
let someOver_20 = numbers.some(arrayFunction);

function arrayFunction(value, index, array) {
return value > 20;
}

JavaScript Array indexOf ()

The indexOf() function returns the location of an element value found in an array.

The first item is in position 0, the second in position 1, etc.

Example: Find the item “Lenovo” in an array:

const computers =["HP", "Lenovo", "IBM"];
let position = computers.indexOf("Lenovo") + 1;

array.indexOf(item, start)

Negative values will begin counting and search to the end at the provided point. If the item cannot be found, Array.indexOf() returns -1. If the item appears multiple times, then the first encounter is returned.

JavaScript Array lastIndexOf()

Array.lastIndexOf() returns the location of the last occurrence of the supplied element, whereas Array.indexOf() returns the initial position of the first item of the specified element.

const computers = ["HP", "Lenovo", "IBM"];
let position = computers.lastIndexOf("Lenovo") + 1;

Array find() in JavaScript

There could be several values when seeking a value that meets specific criteria. However, to return the very first value, we use find(). The example below illustrates how the first encounter of the value greater than 20 is returned from a given array.

const nums = [50, 9, 14, 21, 30];
let first = nums.find(arrayFunction);

function arrayFunction(value, index, array) {
return value > 20;
}

Array findIndex() in JavaScript

The value returned by findIndex() is the first that meets the specified conditions even when the same value could be in the array multiple times. This example retrieves the first element’s index that is greater than 30:

const nums = [50, 9, 14, 21, 30];
let first = nums.findIndex(arrayFunction);

function arrayFunction(value, index, array) {
return value > 30;
}

Array.from() in JavaScript

From any object having a length property or any iterable object, the Array.from() function returns an Array object.

Example: From a String, create an Array:

Array.from("XWYZBQA");

Array Keys() in JavaScript

The Array.keys() method returns an Array Iterator object with an array’s keys.

Example: Create an Array Iterator object that contains the array’s keys:

const computers = ["HP", "Lenovo", "IBM"];
const keys = computers.keys();

for (let x of keys) {
console.log(x);
}

The JavaScript Array includes()

The array was introduced in ECMAScript 2016. includes() is a function that is applied to arrays. It lets us see if an element in an array exists including NaN, unlike indexOf.

const computers = ["HP", "Lenovo", "IBM"];

computers.includes("Lenovo"); // is true

Array Methods in JavaScript

Arrays to Strings Conversion

The toString() method in JavaScript transforms an array into a string of (comma separated) array values.

const computers = ["HP", "Lenovo", "IBM"];
console.log(computers.toString())

The join() method also creates a string from all array items. It works similarly to toString(), but you may also supply a separator:

const computers = ["HP", "Lenovo", "IBM"];
console.log(computers.join(" * "));

Array pop() in JavaScript

The pop() method is used to get rid of the last element in an array. The value that was “popped out” is returned by the pop() method.

const computers = ["HP", "Lenovo", "IBM"];
let computer = computers.pop();

Array push() in JavaScript

The push() method (at the end) adds a new element to an array. The new array length is returned by the push() method:

const computers = ["HP", "Lenovo", "IBM"];
let length = computers.push("Dell");

Array shift() in JavaScript

The shift() method “shifts” the other elements to a lower index by removing the initial array element. The “shifted out” value is returned by the shift() method:

const computers = ["HP", "Lenovo", "IBM"];
let computer = computers.shift();

Array unshift() in JavaScript

The unshift() method “unshifts” older elements and adds a new element to an array at the beginning. The new array length is returned by the unshift() method.

const computers = ["HP", "Lenovo", "IBM"];
computers.unshift("Dell");

Array delete() in JavaScript

The JavaScript operator delete is used to delete array elements. Using delete leaves the array with undefined holes. Instead, use pop() or shift().

const computers = ["HP", "Lenovo", "IBM"];
delete computers[0];

Concatenating (Merging) Arrays

The concat() method merges (concatenates) existing arrays to generate a new one.

const front_end = ["JavaScript", "CSS"];
const backend = ["Python", "PHP", "Java"];
const full_stack = front_end.concat(backend);

Array splice() in JavaScript

To add new elements to an array, use the splice() method:

const computers = ["HP", "Lenovo", "IBM"];
computers.splice(2, 0, "Dell", "Chromebook");

Removing elements with splice()

splic() removes array elements without leaving “holes” in it if you configure the parameters carefully:

const computers = ["HP", "Lenovo", "IBM"];
computers.splice(0, 1);

Array slice() in JavaScript

The slice() method is responsible for creating a new array by slicing a section of an array. Starting with array element 1 (“HP”), this example slices out a section of an array:

const computers = ["HP", "Lenovo", "IBM"];
const micro_soft = computers.slice(1);

Automatic toString()

When a primitive value is expected, JavaScript automatically transforms an array to a comma-separated string. When you try to produce an array, this is always the case. Both of these scenarios will have the same result:

const computers = ["HP", "Lenovo", "IBM"];
console.log(computers.toString());

JavaScript Array Const

ECMAScript 2015 is a new version of ECMAScript (ES6) JavaScript that introduced a crucial new keyword in 2015: const. The use of const while declaring arrays has become commonplace.

Reassignment is not possible

It’s impossible to reassign an array declared with const:

const computers = ["HP", "Lenovo", "IBM"];
computers = ["Dell", "Chromebook"];

Arrays aren’t the same as constants. The keyword const can be deceiving. In fact, it does not include a constant array definition. As a result, it establishes a constant array reference. We can still alter the elements of a constant array because of this.

It’s Possible to Reassign Elements

A constant array’s elements can be changed as follows:

// You can create a constant array:
const computers = ["HP", "Lenovo", "IBM"];


// You can change an element:
computers[0] = "Dell";

// You can add an element:
computers.push("Chromebook");

When JavaScript const variables are declared, they must have a value assigned to them. Meaning that when an array is declared using const, it must be initialized. It’s a syntactic mistake to use const without first initializing the array:

const computers;
computers = ["HP", "Lenovo", "IBM"];

Arrays with the var keyword are initialized at any moment. Even before the array is declared, you can utilize it:

computers = ["HP", "Lenovo", "IBM"];
var computers;

Scope of the Const Block

Block Scope applies to an array specified with const. An array declared inside a block differs from one declared outside the block:

const computers = ["HP", "Lenovo", "IBM"];
// Here computers[0] is "HP"
{
  const computers = ["Dell", "Lenovo", "IBM"];
  // Here computers[0] is "Dell"
}
// Here computers[0] is "HP"

Arrays that have been redeclared

Anywhere in a program, you can redeclare an array declared using var:

var computers =["HP", "Lenovo", "IBM"]; // Allowed
var computers = ["DELL", "Chromebook"]; // Allowed
computers = ["Dell", "Chromebook"]; // Allowed

It’s not possible to redeclare or reassign an array to const in the same scope or block:

var computers = ["Dell", "Chromebook"]; // Allowed
const computers = ["Dell", "HP"]; // Not allowed
{
  var computers = ["Dell", "HP"]; // Allowed
  const computers = ["Dell", "Chromebook"]; // Not allowed
}

It’s not possible to redeclare or reassign an existing const array in the same scope or block:

const computers = ["Dell", "HP"]; // Allowed
const computers = ["Dell", "HP"]; // Not allowed
var computers = ["Dell", "HP"]; // Not allowed
computers = ["Dell", "HP"]; // Not allowed

{
const computers = ["Dell", "HP"]; // Allowed
const computers = ["Dell", "HP"]; // Not allowed
var computers = ["Dell", "HP"]; // Not allowed
computers = ["Dell", "HP"]; // Not allowed
}

It is permissible to redeclare an array with const, in a different scope, or a different block:

const computers = ["Dell", "HP"]; // Allowed
{
  const computers = ["Dell", "HP"]; // Allowed
}
{
  const computers = ["Dell", "HP"]; // Allowed
}

Similar Posts

Leave a Reply

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