Skip to main content
โšก Calmops

JavaScript Arrays: Creation, Indexing, Methods

JavaScript Arrays: Creation, Indexing, Methods

Arrays are ordered collections of values. They’re one of the most important data structures in JavaScript.

Creating Arrays

Array Literal

The most common way:

const colors = ["red", "green", "blue"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "text", true, null];
const empty = [];

Array Constructor

Less common, but useful in some cases:

const arr = new Array(5); // Creates array with 5 empty slots
const arr2 = new Array(1, 2, 3); // Creates [1, 2, 3]

Array.from()

Convert iterable to array:

const str = "hello";
const arr = Array.from(str);
console.log(arr); // ["h", "e", "l", "l", "o"]

const set = new Set([1, 2, 3]);
const arr2 = Array.from(set);
console.log(arr2); // [1, 2, 3]

Indexing

Access elements by position (0-based):

const fruits = ["apple", "banana", "orange"];

console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "orange"
console.log(fruits[3]); // undefined

Negative Indexing (ES2022)

Access from the end:

const arr = [1, 2, 3, 4, 5];

console.log(arr.at(-1)); // 5 (last element)
console.log(arr.at(-2)); // 4 (second to last)
console.log(arr.at(0)); // 1 (first element)

Array Properties

length

Get or set array length:

const arr = [1, 2, 3];
console.log(arr.length); // 3

arr.length = 5;
console.log(arr); // [1, 2, 3, empty, empty]

arr.length = 2;
console.log(arr); // [1, 2]

Modifying Arrays

Adding Elements

const arr = [1, 2, 3];

// Add to end
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

// Add to beginning
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3, 4]

// Add at specific index
arr[2] = 99;
console.log(arr); // [0, 1, 99, 3, 4]

Removing Elements

const arr = [1, 2, 3, 4, 5];

// Remove from end
arr.pop();
console.log(arr); // [1, 2, 3, 4]

// Remove from beginning
arr.shift();
console.log(arr); // [2, 3, 4]

// Remove at specific index
arr.splice(1, 1); // Remove 1 element at index 1
console.log(arr); // [2, 4]

splice() Method

Remove and/or insert elements:

const arr = ["a", "b", "c", "d"];

// Remove 2 elements starting at index 1
arr.splice(1, 2);
console.log(arr); // ["a", "d"]

// Insert elements
const arr2 = ["a", "b", "d"];
arr2.splice(2, 0, "c"); // Insert "c" at index 2
console.log(arr2); // ["a", "b", "c", "d"]

// Replace elements
const arr3 = ["a", "b", "c"];
arr3.splice(1, 1, "x", "y"); // Replace "b" with "x", "y"
console.log(arr3); // ["a", "x", "y", "c"]

Searching Arrays

indexOf()

Find first occurrence:

const arr = [10, 20, 30, 20, 40];

console.log(arr.indexOf(20)); // 1
console.log(arr.indexOf(99)); // -1 (not found)

lastIndexOf()

Find last occurrence:

const arr = [10, 20, 30, 20, 40];

console.log(arr.lastIndexOf(20)); // 3

includes()

Check if element exists:

const arr = ["apple", "banana", "orange"];

console.log(arr.includes("banana")); // true
console.log(arr.includes("grape")); // false

find()

Find first element matching condition:

const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" }
];

const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: "Bob" }

findIndex()

Find index of first matching element:

const arr = [5, 12, 8, 130, 44];

const index = arr.findIndex(x => x > 10);
console.log(index); // 1 (12 is at index 1)

Slicing Arrays

slice()

Extract portion without modifying original:

const arr = [1, 2, 3, 4, 5];

console.log(arr.slice(1, 4)); // [2, 3, 4]
console.log(arr.slice(2)); // [3, 4, 5]
console.log(arr.slice(-2)); // [4, 5]
console.log(arr); // [1, 2, 3, 4, 5] (unchanged)

Combining Arrays

concat()

Combine arrays:

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];

const combined = arr1.concat(arr2, arr3);
console.log(combined); // [1, 2, 3, 4, 5, 6]
console.log(arr1); // [1, 2] (unchanged)

Spread Operator

Modern way to combine:

const arr1 = [1, 2];
const arr2 = [3, 4];

const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]

// Add elements
const withExtra = [...arr1, 99, ...arr2];
console.log(withExtra); // [1, 2, 99, 3, 4]

Sorting Arrays

sort()

Sort in place:

const arr = [3, 1, 4, 1, 5];
arr.sort();
console.log(arr); // [1, 1, 3, 4, 5]

Custom Sort

const numbers = [10, 5, 40, 25];

// Ascending
numbers.sort((a, b) => a - b);
console.log(numbers); // [5, 10, 25, 40]

// Descending
numbers.sort((a, b) => b - a);
console.log(numbers); // [40, 25, 10, 5]

Sort Objects

const users = [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 35 }
];

users.sort((a, b) => a.age - b.age);
console.log(users);
// [{ name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]

Reversing Arrays

reverse()

Reverse in place:

const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // [5, 4, 3, 2, 1]

Joining Arrays

join()

Convert array to string:

const arr = ["apple", "banana", "orange"];

console.log(arr.join()); // "apple,banana,orange"
console.log(arr.join(" - ")); // "apple - banana - orange"
console.log(arr.join("")); // "applebananaorange"

Practical Examples

Remove Duplicates

const arr = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]

Flatten Nested Array

const nested = [1, [2, 3], [4, [5, 6]]];
const flat = nested.flat(2); // Depth of 2
console.log(flat); // [1, 2, 3, 4, 5, 6]

Check if All Elements Match

const arr = [2, 4, 6, 8];
const allEven = arr.every(x => x % 2 === 0);
console.log(allEven); // true

Check if Any Element Matches

const arr = [1, 3, 5, 8];
const hasEven = arr.some(x => x % 2 === 0);
console.log(hasEven); // true

Summary

  • Create: array literals, Array constructor, Array.from()
  • Access: indexing with [index], .at() for negative indexing
  • Modify: push, pop, shift, unshift, splice
  • Search: indexOf, includes, find, findIndex
  • Slice: slice() without modifying original
  • Combine: concat, spread operator
  • Sort: sort() with custom comparator
  • Join: join() to create string

Official Documentation

Next Steps

  1. Array Methods: map, filter, reduce, forEach
  2. Destructuring: Arrays and Objects
  3. JavaScript Objects: Creation, Properties, Methods

Comments