js array slice and splice code example
Example 1: javascript slice array
// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]
// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]
Example 2: use of slice and splice add elements array
function frankenSplice(arr1, arr2, n) {
// Create a copy of arr2.
let combinedArrays = arr2.slice()
// [4, 5, 6]
// Insert all the elements of arr1 into arr2 beginning
// at the index specified by n. We're using the spread
// operator "..." to insert each individual element of
// arr1 instead of the whole array.
combinedArrays.splice(n, 0, ...arr1)
// (1, 0, ...[1, 2, 3])
// [4, 1, 2, 3, 5, 6]
// Return the combined arrays.
return combinedArrays
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
Example 3: array.slice
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
Example 4: array.splice javascript
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
months.splice(0, 1);
// removes 1 element at index 0
console.log(months);
// expected output: Array ["Feb", "March", "April", "May"]