Which Array method to use in JS?
Naresh Tallapaka
Posted on September 20, 2024
- To mutate the original Array:
- push() Description: Adds one or more elements to the end of an array.
js
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
- pop() Description: Removes the last element from an array and returns that element.
js
const fruits = ['apple', 'banana', 'orange'];
const lastFruit = fruits.pop();
console.log(fruits); // Output: ['apple', 'banana']
console.log(lastFruit); // Output: 'orange'
- shift() Description: Removes the first element from an array and returns that element.
js
const fruits = ['apple', 'banana', 'orange'];
const firstFruit = fruits.shift();
console.log(fruits); // Output: ['banana', 'orange']
console.log(firstFruit); // Output: 'apple'
- unshift() Description: Adds one or more elements to the beginning of an array.
js
const fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
- splice() Description: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
js
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'kiwi', 'mango'); // Removes 1 element at index 1 and adds 'kiwi' and 'mango'
console.log(fruits); // Output: ['apple', 'kiwi', 'mango', 'orange']
- fill() Description: Fills all the elements of an array from a start index to an end index with a static value.
js
const numbers = [1, 2, 3, 4, 5];
numbers.fill(0, 1, 4); // Fills from index 1 to 4 with 0
console.log(numbers); // Output: [1, 0, 0, 0, 5]
- sort() Description: Sorts the elements of an array in place and returns the sorted array.
js
const numbers = [5, 3, 8, 1];
numbers.sort(); // Sorts numbers as strings by default
console.log(numbers); // Output: [1, 3, 5, 8]
- reverse() Description: Reverses the elements of an array in place.
js
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]
- splice() for Removal Description: You can also use splice() to remove elements without adding any.
js
const fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1); // Removes 1 element at index 1
console.log(fruits); // Output: ['apple', 'orange']
- copyWithin() Description: Shallow copies part of an array to another location in the same array and changes the original array.
js
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3); // Copies elements from
index 3 to 0
console.log(numbers); // Output: [4, 5, 3, 4, 5]
๐ ๐ช ๐
๐ฉ
Naresh Tallapaka
Posted on September 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev 5 Best Reasons You Should Choose Microservices Architecture for Your Project
November 2, 2024