Javascript Arrays
Array Methods
Array ForEach
const numbers = [1, 2, 3, 4, 5]
numbers.forEach(number => console.log(number));
$ 1
$ 2
$ 3
$ 4
$ 5
Acts on each member of the array.
Array Map
const numbers = [1, 2, 3, 4, 5];
const newNumber = numbers.map((number) => number + 1);
console.log(newNumber);
Returns a new array.
Array Filter
const numbers = [1, 2, 3, 4, 5]
const filteredNumbers = numbers.filter(number => number < 3);
console.log(filteredNumbers)
$ [1, 2]
Returns a new array
Array Find
Array Includes
const numbers = [1, 2, 3, 4, 5]
numbers.includes(2);
$ true
Returns a boolean
Array Sort
const numbers = [1, 2, 3, 4, 5];
const sortedArray = numbers.sort((a, b) => b - a);
console.log(sortedArray);
$ [5, 4, 3, 2, 1] // <== b - a sorts descending, a - b sorts ascending
Array Some and Every
const numbers = [1, 2, 3, 4, 5];
const some = numbers.some((number) => number < 3);
const every = numbers.every((number) => number < 3);
console.log(some);
console.log(every);
$ true
$ false
Array Reduce
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, number) => accumulator + number);
console.log(sum);
Performs an action on each round and stores the value in the accumulator. The accumulator starts with the value of the first member of the array.
Array Reverse
const numbers = [1, 2, 3, 4, 5];
const reversedArray = numbers.reverse();
console.log(reversedArray);
$ [5, 4, 3, 2, 1]
Array Concat
const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = [6, 7, 8, 9, 10];
const concatArr = numbers1.concat(numbers2);
console.log(concatArr);
$ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Backlinks
Javascript - Tricky Bits
- [[javascript-arrays]]
Javascript
- [[javascript-arrays]]