Arrays - methods Flashcards
.concat()
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let newArray = arr1.concat(arr2);
console.log(newArray); // outputs [1, 2, 3, 4, 5, 6]
.slice()
let arr = [1, 2, 3, 4, 5];
let newArray = arr.slice(1, 3);
console.log(newArray); // outputs [2, 3]
.splice()
let arr = [1, 2, 3, 4, 5];
arr.splice(1, 2, 6, 7);
console.log(arr); // outputs [1, 6, 7, 4, 5]
The .splice() method modifies the original array by adding, removing, or replacing elements. It takes three arguments:
start: the index at which to start changing the array.
deleteCount: the number of elements to be removed.
element1, element2, …: the elements to be added to the array.
It returns an array containing the removed elements (if any).
Example:
javascript
Copy code
let arr = [1, 2, 3, 4, 5];
let removed = arr.splice(2, 2, 6, 7);
console.log(arr); // outputs [1, 2, 6, 7, 5]
console.log(removed); // outputs [3, 4]
In this example, the .splice() method removes two elements (index 2 and 3) from the arr array and replaces them with two new elements (6 and 7). The method returns the removed elements in the removed array.
.sort()
let arr = [3, 1, 5, 2, 4];
arr.sort();
console.log(arr); // outputs [1, 2, 3, 4, 5]
.reverse()
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr); // outputs [5, 4, 3, 2, 1]
.map()
let arr = [1, 2, 3, 4, 5];
let newArray = arr.map(x => x * 2);
console.log(newArray); // outputs [2, 4, 6, 8, 10]
.filter()
let arr = [1, 2, 3, 4, 5];
let newArray = arr.filter(x => x % 2 === 0);
console.log(newArray); // outputs [2, 4]
.reduce()
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // outputs 15
This method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
Example:
.reduce()
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // outputs 15
This method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
Example:
.forEach()
let arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));
// outputs:
// 1
// 2
// 3
// 4
// 5
.Shift()
let arr = [1, 2, 3, 4, 5];
let first = arr.shift();
console.log(arr);
// outputs: [2, 3, 4, 5]
console.log(first);
// outputs: 1
.unshift()
let arr = [1, 2, 3, 4, 5];
let len = arr.unshift(0);
console.log(arr);
// outputs: [0, 1, 2, 3, 4, 5]
console.log(len);
// outputs: 6
.pop()
let arr = [1, 2, 3, 4, 5];
let last = arr.pop();
console.log(arr);
// outputs: [1, 2, 3, 4]
console.log(last);
// outputs: 5
.push()
let arr = [1, 2, 3, 4, 5];
let len = arr.push(6);
console.log(arr);
// outputs: [1, 2, 3, 4, 5, 6]
console.log(len);
// outputs: 6