Building on our understanding of basic array methods, let’s dive into some advanced array methods: slice() and splice(). These methods are powerful tools for manipulating arrays in JavaScript.
Slice( ) : Return a Piece of the Array
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). The original array is not modified.
Syntex:
array.slice(startIdx, endIdx)
Example:
let fruits = ["apple", "banana", "orange", "mango"];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ["banana", "orange"]
console.log(fruits); // Output: ["apple", "banana", "orange", "mango"]
Splice( ) : Change Original Array
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. This method modifies the original array.
Syntex:
array.splice(startIdx, delCount, newEl1, newEl2, ...)
Example 1:Removing Elements
let fruits = ["apple", "banana", "orange", "mango"];
let removedFruits = fruits.splice(1, 2);
console.log(removedFruits); // Output: ["banana", "orange"]
console.log(fruits); // Output: ["apple", "mango"]
Example 2: Adding Elements
let fruits = ["apple", "banana"];
fruits.splice(1, 0, "orange", "mango");
console.log(fruits); // Output: ["apple", "orange", "mango", "banana"]
Example 3: Replacing Elements
let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "mango");
console.log(fruits); // Output: ["apple", "mango", "orange"]
Summary:
These advanced methods provide more flexibility compared to basic array methods. slice() allows you to create new arrays from portions of existing ones without altering the original array, making it ideal for working with subsets of data. splice(), on the other hand, enables you to add, remove, or replace elements within the original array, offering powerful in-place modifications that are not possible with simpler methods
Top comments (0)