244

What is the difference between splice and slice?

$scope.participantForms.splice(index, 1);
$scope.participantForms.slice(index, 1);
Omar Einea
  • 2,410
  • 6
  • 21
  • 34
Renat Gatin
  • 4,658
  • 3
  • 30
  • 50
  • 3
    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. – mrunion Jun 02 '16 at 20:21
  • 1
    check if this aswer helps you http://stackoverflow.com/questions/1777705/a-question-about-javascripts-slice-and-splice-methods – Fábio Luiz Jun 02 '16 at 20:22
  • The splice() methods mutate an array by either adding to the array or removing from an array and returns only the removed items. – Shaik Md N Rasool Jul 12 '20 at 02:35
  • They should have interchanged names to communicate their actual meaning e.g. slice piece of cake - cut big cake and give away a portion. But in reality it does exactly opposite by keeping original cake intact and giving a slice of it, how is it possible argh. – vikramvi Aug 12 '20 at 07:38
  • When you have a sandwich, what you really do is have two splices, not two slices. You will have reduced the loaf by doing so. Unintuitive, I know. – Dean Apr 20 '21 at 03:31

15 Answers15

329

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:

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

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


console.log("----after-----");
console.log(array);
console.log(array2);
saketh
  • 720
  • 1
  • 6
  • 18
Thalaivar
  • 20,946
  • 5
  • 57
  • 67
  • 31
    It's also important to observe that the slice() array method can be used to copy arrays by not passing any arguments `arr1 = arr0.slice()` – Mg Gm Apr 06 '19 at 11:35
  • 9
    You can think of it like `splice` is like a government taking taxes from you. Whereas `slice` is more a copy-paste guy. – radbyx Jan 14 '20 at 11:10
  • 4
    `.splice()` is **extremely** unintuitive, I just spent ages trying to figure out why references to the original array were returning `undefined` until I found this thread. – Nixinova Jun 13 '20 at 04:06
  • **splice** or like I tend to say _"**slice** and **p**lunder the values from the caller"_. – Martin Braun Apr 20 '21 at 20:01
75

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.

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]

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.

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]
Gagandeep Gambhir
  • 3,063
  • 23
  • 30
  • 5
    Though both functions perform quite different tasks, unlike `splice(x,y)`, in `slice(x,y)` the second argument `y` is not counted from the position of x, but from the first element of the array. – Ramesh Pareek May 06 '18 at 02:57
  • One more thing I noted : instead of `array.slice(index, count)`, if you use `array.slice((index, count))`, you will get the remaining part after 'slicing'. Try it! – Ramesh Pareek May 06 '18 at 13:28
31

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

Sajeetharan
  • 186,121
  • 54
  • 283
  • 331
  • 3
    It's more than just how you specify arguments. One of them (splice) modifies the base array and the other one does not. – Arbiter Jul 09 '19 at 14:31
  • 1
    also could think of splice as split (generates 2 arrays) + slice –  Nov 06 '19 at 01:22
24

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.

Alexander Kravets
  • 3,405
  • 13
  • 14
  • Can anyone give helpful examples and what would be ideal for each? Like situations that you prefer to use splice or slice? – petrosmm Jul 18 '18 at 13:24
  • 2
    this answer is partially incorrect. for `splice` the 2nd arg is count of elements in return array , but for `slice` the 2nd arg is the index of the final element to return + 1. `slice(index,1)` doesn't necessarily return an array of one element starting at `index`. `[1,2,3,4,5].slice(0,1)` returns `[1]` but `[1,2,3,4,5].slice(3,1)` returns `[]` because `1` is interpreted as `final index +1` so `final index = 0` but this is before `start index = 3` so empty array is returned. – BaltoStar Jul 07 '19 at 18:20
  • Why is this not the top answer? – JJ Labajo Jul 30 '19 at 09:30
23

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.

vikramvi
  • 1,521
  • 4
  • 25
  • 45
15

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:

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 ]

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:

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 ]

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

Community
  • 1
  • 1
taguenizy
  • 1,922
  • 1
  • 6
  • 23
14

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.

Iñigo
  • 1,376
  • 2
  • 18
  • 41
  • per docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice slice doesnt require arguments – cikatomo Nov 26 '20 at 23:56
12

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.

mrunion
  • 913
  • 6
  • 13
  • 3
    Splice _deletes_ the specified number and then inserts any subsequent arguments. – Josiah Keller Jun 02 '16 at 20:22
  • splice deletes a given number of elements from a given start index e.g. splice(4,1); deletes one element starting from index 4 whereas splice(4,3); deletes three elements starting with the element at index 4. Then after deleting them it returns the deleted values. – briancollins081 Nov 13 '19 at 11:58
5

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);

let log = console.log;

//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]

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

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

enter image description here

xgqfrms
  • 5,516
  • 1
  • 37
  • 42
3

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]
3

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.

dev verma
  • 383
  • 1
  • 3
  • 12
3

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

snr
  • 13,515
  • 2
  • 48
  • 77
2

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

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


console.log("----after-----");
console.log(array);
console.log(array2);
1

JavaScript Array splice() Method By Example

Example1 by tutsmake -Remove 2 elements from index 1

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

 arr.splice(1,2);

 console.log( arr ); 

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

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

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

 console.log( arr );  

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

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);

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

Developer
  • 622
  • 6
  • 5
1

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)
David Lin
  • 12,681
  • 5
  • 43
  • 41