xxxxxxxxxx
splice() method changes the original array.
slice() method doesn't change the original array.
both returned selected elements.
xxxxxxxxxx
var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
console.log(array2.slice(-2,4));
// shows [9]
console.log(array2.slice(-3,-1));
// shows [8, 9]
console.log(array2);
// shows [6, 7, 8, 9, 0]
xxxxxxxxxx
/*-------------slice and splice-------------*/
let myArray = [1, 2, 3, 4, 5]
let myArray2 = myArray.slice(1, 3)
console.log('myArray', myArray) // does not modify original array
console.log('myArray2', myArray2) // return new array , what is deleted
console.log('------------', )
let myArray3 = [1, 2, 3, 4, 5]
let myArray4 = myArray3.splice(1, 3)
console.log('myArray3', myArray3) // modify original array , what left after deletion
console.log('myArray4', myArray4) // return new array , what is deleted
xxxxxxxxxx
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
var array3=[11,12,13,14,15];
console.log(array3.splice(2,1,"Hello","World"));
// shows [13]
console.log(array3);
// shows [11, 12, "Hello", "World", 14, 15]
-5 -4 -3 -2 -1
| | | | |
var array4=[16,17,18,19,20];
| | | | |
0 1 2 3 4
console.log(array4.splice(-2,1,"me"));
// shows [19]
console.log(array4);
// shows [16, 17, 18, "me", 20]
xxxxxxxxxx
Lets take an array const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Doing slice operation on the following array will result in the output:-
console.log(arr.slice(0, 3))
[ 0, 1, 2 ]
console.log(arr.slice(3))
[3, 4, 5, 6, 7, 8, 9]
console.log(arr.slice(-3))
[ 7, 8, 9 ]
console.log(arr.slice(-4,-1))
[ 6, 7, 8 ]
slice() returns a potion of an array or makes a shallow copy of the array
-----------------------------------------
However the splice() operation modifies the original
array by removing or replacing elements.
Its syntax is:
splice(start, optional delete count, optional items to add)
const food = ['pizza', 'cake', 'salad', 'cookie'];
food.splice(1,0,"biriyani")
The result would be -
['pizza', 'biriyani', 'cake', 'salad', 'cookie'];
but remember this pretty important point - This makes changes to
the original array and it only returns the deleted
elements if we console.log it.
If we console.log(food.splice(1,0,"biriyani")),
then we would get back an empty array because
nothing was removed from our array.