Arrays
const fruits = ['apple', 'orange', 'banana'];
// Different data types
const data = [1, 'chicken', false];Property .length
const numbers = [1, 2, 3, 4];
numbers.length; // 4Index
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200Mutable chart
| add | remove | start | end | |
|---|---|---|---|---|
push | ✔ | ✔ | ||
pop | ✔ | ✔ | ||
unshift | ✔ | ✔ | ||
shift | ✔ | ✔ |
Array.push()
// Adding a single element:
const cart = ['apple', 'orange'];
cart.push('pear');
// Adding multiple elements:
const numbers = [1, 2];
numbers.push(3, 4, 5);Add items to the end and returns the new array length.
Array.pop()
const fruits = ['apple', 'orange', 'banana'];
const fruit = fruits.pop(); // 'banana'
console.log(fruits); // ["apple", "orange"]Remove an item from the end and returns the removed item.
Array.shift()
let cats = ['Bob', 'Willy', 'Mini'];
cats.shift(); // ['Willy', 'Mini']Remove an item from the beginning and returns the removed item.
Array.unshift()
let cats = ['Willy', 'Bob']; //['Willy', 'Bob']
cats.unshift('Willy'); // ['Bob']Add items to the beginning and returns the new array length.
Array.concat()
const numbers = [3, 2, 1];
const newFirstNumber = 4; // => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers); // => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber);If you want to avoid mutating your original array, you can use concat.
Array.reduce()
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, curVal) => {
return accumulator + curVal;
});
console.log(sum); // 10Array.map()
const members = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
const announcements = members.map((member) => {
return member + ' joined the contest.';
});
console.log(announcements);Array.forEach()
const numbers = [28, 77, 45, 99, 27];
numbers.forEach((number) => {
console.log(number);
});Array.filter()
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter((n) => {
return n > 5;
});