Day 4 -Difference between slice() and splice() in javascript!

Day 4 -Difference between slice() and splice() in javascript!

slice() and splice() are both methods on javascript arrays!

slice()

slice() copies the items from the original array and returns the elements the selected elements. The original array remains unaffected when using slice().

The Syntax

slice(start,end)

Params

  • start - specifies the index to start the slicing. The indexing starts from 0. If negative value n is specified, then the last n values will be retrieved.

  • end - specified the index till which elements are to be selected. Not inclusive. If negative value n is specified, then the last n values will be excluded.

Examples

let a=[0,1,2,3,4,5,6,7,8,9];

//Return the elements from 3rd index till 6th index
console.log(a.slice(3,6));  //returns [3, 4, 5]

//Return all the elements from 2nd index
console.log(a.slice(2)); // returns [2, 3, 4, 5, 6, 7, 8, 9]

//Return the last 3 elements
console.log(a.slice(-3)); // returns [7, 8, 9]

//Return all the elements from 1st index except the last 3 elements
console.log(a.slice(1,-3));// returns [1, 2, 3, 4, 5, 6]

splice()

splice() removes the items from the original array and then returns the selected elements. The contents of the original array are also affected when using splice().

The Syntax

splice(start,delete-count, item1, item 2, .... n)

Params

  • start - specifies the index to start the splicing. The indexing starts from 0. If negative value n is specified, then the last n values will be retrieved.
  • delete-count - It's the no. of items that need to be deleted from the original array and returned.
  • item1, item 2, .... n - It's the new items to be added starting from the start index.

Examples

let a=[0,1,2,3,4,5,6,7,8,9];

//Delete the elements from 3rd index till 6th index
console.log(a.splice(3,3));  //returns [3, 4, 5] and a=[0, 1, 2, 6, 7, 8, 9]

//Delete 4 elements from 2nd index
let a=[0,1,2,3,4,5,6,7,8,9];
console.log(a.splice(2,4)); //returns [2, 3, 4, 5] and a=[0, 1, 6, 7, 8, 9]

//Delete all the elements from 2nd index
let a=[0,1,2,3,4,5,6,7,8,9];
console.log(a.splice(2)); // returns [2, 3, 4, 5, 6, 7, 8, 9] and a=[0, 1]

//Delete the last 3 elements
let a=[0,1,2,3,4,5,6,7,8,9];
console.log(a.splice(-3)); // returns [7, 8, 9] and a=[0, 1, 2, 3, 4, 5, 6]

//Delete 2 elements from the 5th index and add 2 new elements
let a=[0,1,2,3,4,5,6,7,8,9];
console.log(a.splice(5,2,"five","six")); // returns [5, 6] and a=[0, 1, 2, 3, 4, 'five', 'six', 7, 8, 9]

//No deletion. Just add 2 new elements before the 6th index
let a=[0,1,2,3,4,5,6,7,8,9];
console.log(a.splice(6,0,5.1,5.2)); // returns [] and a=[0, 1, 2, 3, 4, 5, 5.1, 5.2, 6, 7, 8, 9]