JS Arrays

Create array

    

let letters = ['a', 'b', 'c'];
letters[0]; // Access first item


    

Access item

    

letters[0]; // Access first item
letters[1]; // Access second item


    

Length

    

letters.length;
// Output: 3


    

Add item to end

    

letters.push('d');
// Output: ['a', 'b', 'c', 'd']


    

Remove last item

    

letters.pop();
// Output: ['a', 'b']


    

Add item to beginning

    

letters.unshift('d');
// Output: ['d', 'a', 'b', 'c']


    

Remove first item

    

letters.shift();
// Output: ['b', 'c']


    

Find index of item

    

letters.indexOf('a');
// Output: 0


    

Remove specific item

    

letters.splice(1, 1); // splice(index, number of items)
// Output: ['a', 'c']


    

Replace item(s)

    

letters.splice(1, 1, 'x', 'y', 'z'); // splice(index, number of items)
// Output: ['a', 'x', 'y', 'z', 'c']


    

Reverse

    

letters.reverse();
// Output: ['c', 'b', 'a']


    

Combine arrays

    

let letters = ['a', 'b', 'c'];
let end = ['x', 'y', 'z'];
let newArray = letters.concat(end);
// Output: ['a', 'b', 'c', 'x', 'y', 'z']


    

Array destructuring

    

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


    

Create 2D array

    

let letters = [['a', 'b'], ['c', 'd']];


    

Access items (2D array)

    

letters[0][0]; // Access first item of first array
letters[0][1]; // Access second item of first array
letters[1][0]; // Access first item of second array
letters[1][1]; // Access second item of second array