JavaScript: Array methods
Array Methods
Arrays have many methods that perform different tasks.
1. .push() Method
.push() allows us to add items to the end of an array.
For example, we add numbers 4 and 5 to the array
const numbers = [1, 2, 3];
numbers.push(4, 5);
console.log(numbers);
// Output: [1, 2, 3, 4, 5]
2. .pop() Method
.pop() removes the last item of an array.
const numbers = [1, 2, 3];
const removed = numbers.pop();
console.log(numbers);
// Output: [1, 2]
console.log(removed);
// Output: 3
3. .shift() Method
shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array1 = [1, 2, 3, 4, 5];
const firstElement = array1.shift();
console.log(array1);
// Output: [2, 3, 4, 5]
console.log(firstElement);
// Output: 1
4. .unshift() method
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// Output: 5
console.log(array1);
// Output: Array [4, 5, 1, 2, 3]
5. .splice()
splice() method removes or replaces existing elements and/or adds new elements in place.
array.splice(indexToStart, numberOfIndices, "stringToAdd");
For example:
const months = ["Jan", "March", "April", "May"];
months.splice(1, 0, "Feb");
// inserts at index 1
console.log(months);
// Output: Array ["Jan", "Feb", "March", "April", "May"]
6. .concat()
concat() method creates a new array by merging existing arrays.
let a = [1, 2];
let b = [3, 4, 5];
let c = a.concat(b);
7. .slice()
slice() method slices out a piece of an array into a new array from start to end (end not included).
let array1 = [0, 1, 2, 3, 4, 5];
let num = array1.slice(1, 4);
// Output: [1, 2, 3]
8. reverse()
reverse() method reverses the elements in an array. arr.reverse();
9. Check if it’s an array
To check if something is an array, we use Array.isArray() method
const numbers = [1, 2, 3];
console.log(Array.isArray(numbers)); // true
console.log(Array.isArray("hello")); // false because it's a string
10. Check the index
To check the index of an item in an array, we use indexOf().
const names = ["Anna", "Pete", "Jane", "Luna"];
console.log(names.indexOf("Jane")); // 2
Comments
Post a Comment