Skip to content

Arrays in JavaScript

Array Literals

This is the most common way to create an array in JavaScript. An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]).

let arr = [1, 2, 3, 4, 5];
const n = 5; // Replace with your desired length
const zeroArray = Array(n).fill(0); //0-array of length 5

Accessing Elements

You can access elements of an array by referring to the index number.

console.log(arr[0]);  // Outputs: 1

Array Length

The length property returns the number of elements in an array.

console.log(arr.length);  // Outputs: 5

Adding Array Elements

You can add an element to an array by specifying the index number.

arr[5] = 6;  // Adds a new element to the array at index 5

Looping Over an Array

You can loop over an array using the for loop or the forEach method.

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

// OR

arr.forEach(function(element) {
    console.log(element);
});

Array Methods

JavaScript arrays have lots of built-in methods for manipulating arrays, such as push (add elements), pop (remove last element), shift (remove first element), unshift (add to the front), concat (merge arrays), slice (return selected elements), and splice (add/remove elements), among others.

arr.push(7);  // Adds a new element to the end of the array
let lastElement = arr.pop();  // Removes the last element from the array

let array = [1, 2, 3, 4, 5];
array.splice(2, 1); // Removes 1 element at index 2
console.log(array); // Output: [1, 2, 4, 5]

Checking if an array contains an element

let array = [1, 2, 3, 4, 5];
console.log(array.includes(3)); // Output: true
//or
let array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3) !== -1); // Output: true
//or
let array = [1, 2, 3, 4, 5];
console.log(array.some(item => item === 3)); // Output: true
//or
let array = [1, 2, 3, 4, 5];
console.log(array.find(item => item === 3) !== undefined); // Output: true

Multidimensional Arrays

JavaScript arrays can contain arrays, which makes them multidimensional.

let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Array Destructuring

ES6 introduced destructuring, which allows you to unpack values from arrays, or properties from objects, into distinct variables.

let [a, b] = arr;  // a = 1, b = 2

Spread Operator

The spread operator (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

let arr2 = [...arr, 7, 8, 9];  // arr2 is now [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sorting arrays

You can sort an array of numbers correctly in JavaScript using the sort() method, but you need to provide a custom compare function. By default, sort() treats array elements as strings, which leads to incorrect numerical sorting.

Here's how to do it:

Using a Compare Function

The sort() method accepts an optional compare function. This function takes two arguments (a and b) and should return:

  • A negative value if a should come before b.
  • A positive value if a should come after b.
  • Zero if a and b are considered equal.

For numerical sorting, you can simply subtract b from a:

const numbers = [4, 2, 5, 1, 3, 10, 100, 50];

numbers.sort(function(a, b) {
  return a - b; // Ascending order
});

console.log(numbers); // Output: [1, 2, 3, 4, 5, 10, 50, 100]

Shortened Version (Arrow Function):

const numbers = [4, 2, 5, 1, 3, 10, 100, 50];

numbers.sort((a, b) => a - b); // Ascending order using arrow function

console.log(numbers);

Descending Order

To sort in descending order, simply reverse the subtraction:

const numbers = [4, 2, 5, 1, 3, 10, 100, 50];

numbers.sort((a, b) => b - a); // Descending order

console.log(numbers); // Output: [100, 50, 10, 5, 4, 3, 2, 1]

Why the Default Sort Fails

Without a compare function, sort() treats numbers as strings. For example, "10" comes before "2" because "1" is lexicographically less than "2". This is why [10, 2, 5].sort() would result in [10, 2, 5] without a compare function.

Example with Negative Numbers and Decimals:

const numbers = [-5, 3.2, 10, -1, 0, 5.5];

numbers.sort((a, b) => a - b);

console.log(numbers); // Output: [-5, -1, 0, 3.2, 5.5, 10]

Key Points

  • Always use a compare function when sorting numbers.
  • a - b sorts in ascending order.
  • b - a sorts in descending order.
  • This method handles negative numbers and decimals correctly.