arrow_back
Back

JavaScript Array: methods, iteration, and typed arrays

Andrew Dorokhov Andrew Dorokhov schedule 3 min read
menu_book Table of Contents

All arrays are copied by link.

Creating an array

const arr = [];
const arr = [10, 22, 12, 54];
const arr = [10, 'hello', 12, {answer: 'yes'}];

Elements do not have to share the same type. Nested arrays are fine too:

const mixed = [3, 'dinosaurs', ['triceratops', 'stegosaurus', 3627.5], 10];

Access and rewrite by index:

const test = ['one', 'two', 'three'];
test[0];              // 'one'
test[1] = 'another';  // rewrite

Sparse arrays — assigning far beyond the current length leaves holes (undefined):

test[122] = 'yes';
// ['one', 'two', 'three', empty × 119, 'yes']

Last element:

arr[arr.length - 1];

Delete the third element:

delete arr[2];

Basic methods

arr.pop();          // Remove the last element and return it.
arr.push(18);       // Add an element to the end; returns new length.
arr.shift();        // Remove the first element and return it.
arr.unshift(23);    // Add an element to the beginning; returns new length.

Finding an index

const colors = ['red', 'green', 'blue'];
colors.indexOf('blue');   // 2
colors.indexOf('green');  // 1
colors.indexOf('yellow'); // -1 — not found

If the value appears more than once, indexOf returns the first (leftmost) index.

Working with strings

// Join elements into a string (default delimiter is a comma):
const str = arr.join(', ');
arr.join(' - ');
arr.join(' and ');

Non-string elements are converted to strings before joining:

[11, 14, 79].join(' '); // '11 14 79'
// Split string using a delimeter:
const arr = str.split(', ');

Sorting

// The method changes the array.
arr.sort(); // alphabetically.
arr.sort((a, b) => a - b); // for sorting numbers.
arr.reverse(); // change the order of the elements.

Replacing elements

// Remove `count` elements starting from `index` 
// and replace them to element1...
arr.splice(index, count, element1...);

Copying

Copy part of an array:

arr.slice(begin, end);

Copy all the array:

const newArr = arr.slice(); // When we need to create an array copy instead of copying a link.

Copying an array using the spread operator:

const newArr = [...arr1]; // Way to copy an array.

Concatenating

Elements are appended in order; the originals are not modified:

arr.concat(arr2);
arr.concat(arr2, arr3, arr4);

Using the spread operator:

const arr1 = ['one', 'two', 'three'];
const arr2 = ['apple', 'watermelon', 'cherry'];
const result = [...arr1, ...arr2, 'table'];

Iterating

Classic for:

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

The for-of:

// Comparing to forEach() using this
// method gives ability to use break and continue.
for (let item of arr) {
    console.log(item);
}

The forEach method:

arr.forEach(function(item, index, array) {
    console.log(`${index}: ${item} inside of ${array}`);
});

The filter() method:

const newArray = arr.filter(item => {
    return item.length < 10;
});

The map() method:

const newArray = arr.map(item => item.toLowerCase());

The some() method:

const someElementIsNumber = arr.some(item => typeof(item) === 'number'); // returns boolean

The every() method:

const everyElementIsNumber = arr.every(item => typeof(item) === 'number'); // returns boolean

The reduce() method:

const newArray = arr.reduce((sum, item) => sum + item);

// Initial value of sum is 9.
const newArray = arr.reduce((sum, item) => sum + item, 9);

Create an array from a pseudo-array:

const a = Array.from(pseudoArray);

Destructuring assignment

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

let arr = ["John", "Smith"]

let [firstName, surname] = arr;

Spreading

const arr1 = ['one', 'two', 'three'];

someFunction(...arr1); // Function that receives three arguments.

Checks

Array.isArray(someVar);

// Alternative:
someVar instanceof Array

Example:

if (response.errors instanceof Array && response.errors.length === 0) {
  // ...
}
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

JavaScript Number: integers, floats, and Math

arrow_forward