Difference between splice() and Slice()

Asked

Viewed 11,240 times

16

What is the difference between the functions splice() and slice() of the object Array of JavaScript and when each shall be used?

2 answers

26


As much as they look alike or alike, they operate very differently.

Splice

Operates with 1 or more (undefined parameters). The first parameter is the index from which you should start the deletion, the second the amount of values removed (if not reported, it will remove all values from the index beginning to the end of the array), and the third one onwards will be new values that will come in place of the values removed. Soon:

    var arr = [1, 2, 3, 4, 5]
    var spliced = arr.splice(1, 2, 'banana'); // [2, 3]
    console.log(arr, spliced); // [1, 'banana', 4, 5] [2, 3]

splice changes the array, removing the values inside it and replacing them with other values if requested at the same time.

Slice

The slice has 3 differences from splice. The first and most important is that it does not alter the original array, it only returns an array with the captured values. Soon:

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

The second difference, as you can see in the example above, is that the second value is not the amount of values to be captured, but the index to stop capturing, not included. That is, passing by 1, 3 to the slice, We took Dexes 1 and 2, as 3 is not included. It will also remove all values from the array until the end if not informed. The third difference is that the slice does not accept more than two parameters, contrary to splice, then replaces nothing in the original array.

On the use cases, it depends what you want to do. I believe that with the explanation of how each one works, you can already have an idea.

External links for more information:

Array.prototype.splice()

Array.prototype.Slice()

  • 2

    Good answer. I suggest putting the code examples as snippets to be possible to execute the code.

  • 2

    I believe that "when using one or the other" is in the very difference between the two.

  • 2

    I usually snippet only when I have html included, but anyway, I followed the suggestion and edited.

  • 2

    I will collaborate with my +1 . I just suggest that you always link to reliable documentation such as MDN (W3schools no, please :D)

  • 1

    I’ll follow the suggestion then, thank you all for your help.

3

In Javascript, confuse slice with splice, or vice versa, it is a common mistake. These two functions, although they have similar names, perform two completely different actions.

The first difference is that the Slice method does not modify the array itself that invokes the method, splice yes.

The second difference consists of the arguments. Slice (verb slice) has the syntax arr.slice([índiceInicial[,índiceFinal]]). Both parameters being optional.

While Splice (verb sew) has syntax array.splice(índiceInicio , quantidadeExcluídos[, item1[,item2[,... itemN]]]). The first of the two mandatory parameters is a zero-based index integer that points to the first item to be removed from the current array. The second parameter is another integer that indicates how many sequential items should be removed from the array. Removing items from the array affects the size of the array, and items that are removed are returned by the splice method as a separate array.

You can also use the splice method to replace array items. Optional parameters from the third allow you to offer data elements that must be entered in the array in place of the removed items. Each additional item can have any type of Javascript data. Actually. specifying zero in the second parameter, you can use splice to insert one or more items at any position of the array

Playing with Slice

var mainString = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function showResults() {
	var form = document.forms[0]
	var param1 = parseInt(form.param1.options[form.param1.selectedIndex].value)
	var param2 = parseInt(form.param2.options[form.param2.selectedIndex].value)
	if (!param2) {
		form.result1.value = mainString.slice(param1)
	} else {
		form.result1.value = mainString.slice(param1, param2)
	}
}
<BODY onLoad="showResults()">
<B>Método slice()</B>
<HR>
<TABLE BORDER=1>
<FORM>
<TR><TH>Parâmetos</TH><TH>Resultado</TH></TR>
<TR>
<TD ROWSPAN=3 VALIGN=middle>
(&nbsp;<SELECT NAME="param1" onChange="showResults()">
	<OPTION VALUE=0>0
	<OPTION VALUE=1>1
	<OPTION VALUE=2>2
	<OPTION VALUE=3>3
	<OPTION VALUE=5>5
</SELECT>,
<SELECT NAME="param2" onChange="showResults()">
	<OPTION >(Nenhum)
	<OPTION VALUE=4>4
	<OPTION VALUE=6>6
	<OPTION VALUE=-1>-1
	<OPTION VALUE=-3>-3
	<OPTION VALUE=-10>-10
</SELECT>&nbsp;) </TD>
<TD><INPUT TYPE="text" NAME="result1" SIZE=25></TD>
</TR>
</FORM>
</TABLE>
</BODY>
</HTML>

Examples Splice

var frutas = ["goiaba", "manga", "laranja", "abacate"];
//remove 1 elemento posição 1 (remove manga) 
var frutasRemovida = frutas.splice(1, 1);

var nomes = ["Leo", "inova pixel", "Anderson Carlos Woss", "fernandoandrade", "mengano",  "fulano", "ciclano", "beltrano", "sicrano"];
//remove 3 elementos começando da posição 2 (remove Anderson Carlos Woss, fernandoandrade e mengano) 
var nomesRemovidos = nomes.splice(2, 3);

console.log(frutas);

console.log(frutasRemovida);

console.log(nomes);

console.log(nomesRemovidos);

var numeros = [1, 2, 3, 4, 5];
//remove 1 elemento começando da posição 3 e inclui os elementos "a" "b" a começando da posição 3 
var add = numeros.splice(3,1,"a","b");

console.log(numeros);
console.log(add);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.