Array in JavaScript

To check if an object is an array:

1
Array.isArray();

typeof will not work because we don’t have a type called array in JavaScript, typeof [1, 2] returns "object".

Add Elements to an Array

Beginning

1
numbers.unshift(1, 2, 3);

End

1
numbers.push(1, 2, 3);

Middle

1
2
3
4
5
const startIndex = 0;
const deleteCount = 0;
item1 = "a";
item2 = "b";
numbers.splice(startIndex, deleteCount, item1, item2);

Removing Elements

Beginning

1
const last = numbers.pop();

End

1
const first = numbers.shift();

Middle

1
2
3
const startIndex = 0;
const deleteCount = 2;
numbers.splice(startIndex, deleteCount);

Finding Elements

Primitive Type

1
2
numbers.indexOf(1);
numbers.lastIndexOf(1);

to check if exists, the old fashion:

1
numbers.indexOf(1) !== -1;

Best practice:

1
numbers.includes(1);

All these methods above have a parameter called fromIndex to specify starting from where.

Reference type

Now indexOf() not working because you need to know the address of elements to check if the are the same.

So we use find(), from MDN doc

The find() method returns the value of first element in the array that satisfies the provided testing function, otherwise undefined is returned

1
2
3
const course = courses.find(function (course) {
return (course.name = "math");
});

A brother function is findIndex() which returns the index of the found element instead of the element.

Array Function

From ES6, best practice when writing call back function:

1
const course = courses.find((course) => (course.name = "math"));

You can read it out like reading English: Find course whose name is equal to math.

Emptying an Array

1
2
let numbers = [1, 2, 3];
let another = numbers;

Poor way:

1
numbers.splice(0, numers.length);

Good but sometimes not working way:

1
2
3
numbers = [];
console.log(numbers); // []
console.log(another); // [1, 2, 3]

Now numbers has been cleared but another still points to [1, 2, 3]

Best practice:

1
2
3
numbers.length = 0;
console.log(numbers); // []
console.log(another); // []

Combining and Slicing Arrays

1
2
const first = [1, 2, 3];
const second = [4, 5, 6];

Combining

1
const combined = first.concat(second);

Slicing

1
2
3
const sliced = first.slice(2, 4); // index 2 and 3, total 2 numbers, 4 is not included
const sliced = first.slice(2); // index 2 to the end
const copied = first.slice(); // get a copy

For all above methods no matter concat() or slice(), object element is copied by reference, the elements in the input and output array will point to the same object.

The Spread Operator

From ES6, this is the best practice when combining array:

1
const combined = [...first, 999, ...second];

You can see that we can even add extra numbers when combining.

From ES6, Best practice when copying an array:

1
const copied = [...first];

For Each Loop

An alternative way other than for of loop when iterating an array:

1
2
3
numbers.forEach((number, index) => {
console.log(number, index);
});

Join Arrays

Join an array, get a string with specified seperator

1
2
3
const numbers = [1, 2, 3];
const joined = numbers.join(", ");
console.log(joined); // "1, 2, 3"

join()‘s brother method is split():

1
2
3
4
5
6
const msg = "1 2 3";
const parts = msg.split(" ");
console.log(parts); // ["1". "2". "3"]

const combined = parts.join("-");
console.log(combined); // "1-2-3"

Sorting Array

1
2
const numbers = [2, 3, 1];
console.log(numbers.sort().reverse());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const courses = [
{ id: 0, name: "Math" },
{ id: 1, name: "Art" },
];

courses.sort((a, b) => {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();

if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});

console.log(courses);

Every and Some

1
2
3
const numbers = [1, 2, 3];
const allPositive = numbers.every((number) => number >= 0);
const atLeastOnePositive = numbers.some((number) => number >= 0);

Filter, Mapping and Reducing

From ES6:

1
2
3
4
5
const numbers = [1, 2, 3, -1];

const items = numbers
.filter((number) => number >= 0)
.map((number) => ({ value: number }));

When returning an object using arrow function, remember to wrap the object with () to avoid js engine regard {} as code block.

reduce() reduces an array into a number:

1
2
3
4
5
6
7
8
let sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
); // the second parameter is the initial value of accumulator

// another approach
// if accumulator is not set, it will be numbers[0] and currentValue will be numbers[1]
sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);

Anytime you have an array of values, and you wanna get a single value as the result of iterating the array, think of reduce().