[javascript] JavaScript Array splice vs slice

What is the difference between splice and slice?

$scope.participantForms.splice(index, 1);
$scope.participantForms.slice(index, 1);

This question is related to javascript

The answer is


splice & delete Array item by index

index = 2

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));

console.log("----after-----");
console.log(arr1);
console.log(arr2);

_x000D_
_x000D_
let log = console.log;_x000D_
_x000D_
//splice & will modify the origin array_x000D_
const arr1 = [1,2,3,4,5];_x000D_
_x000D_
//slice & won't modify the origin array_x000D_
const arr2 = [1,2,3,4,5]_x000D_
_x000D_
log("----before-----");_x000D_
log(arr1.splice(2, 1));_x000D_
log(arr2.slice(2, 1));_x000D_
_x000D_
log("----after-----");_x000D_
log(arr1);_x000D_
log(arr2);
_x000D_
_x000D_
_x000D_

enter image description here


Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.


Here is a simple trick to remember the difference between slice vs splice

var a=['j','u','r','g','e','n'];

// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]

//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]

Trick to remember:

Think of "spl" (first 3 letters of splice) as short for "specifiy length", that the second argument should be a length not an index


Splice and Slice both are Javascript Array functions.

Splice vs Slice

  1. The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.

  2. The splice() method changes the original array and slice() method doesn’t change the original array.

  3. The splice() method can take n number of arguments and slice() method takes 2 arguments.

Splice with Example

Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

Argument 3…n: Optional. The new item(s) to be added to the array.

_x000D_
_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
// shows [3, 4, 5], returned removed item(s) as a new array object._x000D_
 _x000D_
console.log(array);_x000D_
// shows [1, 2], original array altered._x000D_
 _x000D_
var array2=[6,7,8,9,0];_x000D_
console.log(array2.splice(2,1));_x000D_
// shows [8]_x000D_
 _x000D_
console.log(array2.splice(2,0));_x000D_
//shows [] , as no item(s) removed._x000D_
 _x000D_
console.log(array2);_x000D_
// shows [6,7,9,0]
_x000D_
_x000D_
_x000D_

Slice with Example

Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

Argument 2: Optional. An integer that specifies where to end the selection but does not include. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

_x000D_
_x000D_
var array=[1,2,3,4,5]_x000D_
console.log(array.slice(2));_x000D_
// shows [3, 4, 5], returned selected element(s)._x000D_
 _x000D_
console.log(array.slice(-2));_x000D_
// shows [4, 5], returned selected element(s)._x000D_
console.log(array);_x000D_
// shows [1, 2, 3, 4, 5], original array remains intact._x000D_
 _x000D_
var array2=[6,7,8,9,0];_x000D_
console.log(array2.slice(2,4));_x000D_
// shows [8, 9]_x000D_
 _x000D_
console.log(array2.slice(-2,4));_x000D_
// shows [9]_x000D_
 _x000D_
console.log(array2.slice(-3,-1));_x000D_
// shows [8, 9]_x000D_
 _x000D_
console.log(array2);_x000D_
// shows [6, 7, 8, 9, 0]
_x000D_
_x000D_
_x000D_


Splice - MDN reference - ECMA-262 spec

Syntax
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

  • start: required. Initial index.
    If start is negative it is treated as "Math.max((array.length + start), 0)" as per spec (example provided below) effectively from the end of array.
  • deleteCount: optional. Number of elements to be removed (all from start if not provided).
  • item1, item2, ...: optional. Elements to be added to the array from start index.

Returns: An array with deleted elements (empty array if none removed)

Mutate original array: Yes

Examples:

_x000D_
_x000D_
const array = [1,2,3,4,5];

// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]

// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
_x000D_
_x000D_
_x000D_

More examples in MDN Splice examples


Slice - MDN reference - ECMA-262 spec

Syntax
array.slice([begin[, end]])
Parameters

  • begin: optional. Initial index (default 0).
    If begin is negative it is treated as "Math.max((array.length + begin), 0)" as per spec (example provided below) effectively from the end of array.
  • end: optional. Last index for extraction but not including (default array.length). If end is negative it is treated as "Math.max((array.length + begin),0)" as per spec (example provided below) effectively from the end of array.

Returns: An array containing the extracted elements.

Mutate original: No

Examples:

_x000D_
_x000D_
const array = [1,2,3,4,5];

// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]

// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
_x000D_
_x000D_
_x000D_

More examples in MDN Slice examples

Performance comparison

Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test


Another example:

[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]

[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]

splice() changes the original array whereas slice() doesn't but both of them returns array object.

See the examples below:

var array=[1,2,3,4,5];
console.log(array.splice(2));

This will return [3,4,5]. The original array is affected resulting in array being [1,2].

var array=[1,2,3,4,5]
console.log(array.slice(2));

This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].

Below is simple fiddle which confirms this:

_x000D_
_x000D_
//splice_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
_x000D_
//slice_x000D_
var array2=[1,2,3,4,5]_x000D_
console.log(array2.slice(2));_x000D_
_x000D_
_x000D_
console.log("----after-----");_x000D_
console.log(array);_x000D_
console.log(array2);
_x000D_
_x000D_
_x000D_


The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object.

The splice() method changes the original array and slice() method doesn’t change the original array.

  • Splice() method can take n number of arguments:

    Argument 1: Index, Required.

    Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

    Argument 3..n: Optional. The new item(s) to be added to the array.

  • slice() method can take 2 arguments:

    Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.

    Argument 2: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.


JavaScript Array splice() Method By Example

Example1 by tutsmake -Remove 2 elements from index 1

_x000D_
_x000D_
  var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ]; 

 arr.splice(1,2);

 console.log( arr ); 
_x000D_
_x000D_
_x000D_

Example-2 By tutsmake – Add new element from index 0 JavaScript

_x000D_
_x000D_
  var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ]; 

 arr.splice(0,0,"zero");

 console.log( arr );  
_x000D_
_x000D_
_x000D_

Example-3 by tutsmake – Add and Remove Elements in Array JavaScript

_x000D_
_x000D_
var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb'); // add at index 1

console.log(months); 

months.splice(4, 1, 'May'); // replaces 1 element at index 4

console.log(months);
_x000D_
_x000D_
_x000D_

https://www.tutsmake.com/javascript-array-splice-method-by-example/


The difference between Slice() and Splice() javascript build-in functions is, Slice returns removed item but did not change the original array ; like,

        // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.slice(index)
        // result=4  
        // after slicing=>  array =[1,2,3,4,5]  (same as original array)

but in splice() case it affects original array; like,

         // (original Array)
        let array=[1,2,3,4,5] 
        let index= array.indexOf(4)
         // index=3
        let result=array.splice(index)
        // result=4  
        // after splicing array =[1,2,3,5]  (splicing affects original array)

S LICE = Gives part of array & NO splitting original array

SP LICE = Gives part of array & SPlitting original array

I personally found this easier to remember, as these 2 terms always confused me as beginner to web development.


_x000D_
_x000D_
//splice_x000D_
var array=[1,2,3,4,5];_x000D_
console.log(array.splice(2));_x000D_
_x000D_
//slice_x000D_
var array2=[1,2,3,4,5]_x000D_
console.log(array2.slice(2));_x000D_
_x000D_
_x000D_
console.log("----after-----");_x000D_
console.log(array);_x000D_
console.log(array2);
_x000D_
_x000D_
_x000D_


The slice() method returns a copy of a portion of an array into a new array object.

$scope.participantForms.slice(index, 1);

This does NOT change the participantForms array but returns a new array containing the single element found at the index position in the original array.

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

$scope.participantForms.splice(index, 1);

This will remove one element from the participantForms array at the index position.

These are the Javascript native functions, AngularJS has nothing to do with them.


Most answers are too wordy.

  • splice and slice return rest of elements in the array.
  • splice mutates the array being operated with elements removed while slice not.

enter image description here


slice does not change original array it return new array but splice changes the original array.

example: var arr = [1,2,3,4,5,6,7,8];
         arr.slice(1,3); // output [2,3] and original array remain same.
         arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].

splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.

arr.splice(-3,-1); // output [] second argument value should be greater then 
0.
arr.splice(-3,-1); // output [6,7] index in minus represent start from last.

-1 represent last element so it start from -3 to -1. Above are major difference between splice and slice method.