push()
The push() method is used to add an element to the end of an array. It returns the new length of the array after the element has been added.
let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
pop()
The pop() method removes the last element from an array and returns it.
let numbers = [1, 2, 3];
let last = numbers.pop();
console.log(last); // 3 console.log(numbers); // [1, 2]
shift()
The shift() method removes the first element from an array and returns it.
let numbers = [1, 2, 3];
let first = numbers.shift();
console.log(first); // 1 console.log(numbers); // [2, 3]
unshift()
The unshift() method adds an element to the beginning of an array and returns the new length of the array.
let numbers = [1, 2, 3];
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3]
splice()
The splice() method allows you to add or remove elements from an array at a specified index.
let numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 2, 6, 7);
console.log(numbers); // [1, 2, 6, 7, 5]
slice()
The slice() method returns a shallow copy of a portion of an array into a new array object.
let numbers = [1, 2, 3, 4, 5];
let subArray = numbers.slice(1, 4); console.log(subArray); // [2, 3, 4]
map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(function(num) { return num * 2; });
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evenNumbers); // [2, 4]
reduce()
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }, 0);
console.log(sum); // Output: 15