Difference between splice () and slice ()

12

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

    
asked by anonymous 19.11.2018 / 17:35

2 answers

17

Although they look the same or similar, they operate quite differently.

Splice

Operates with 1 or more (undefined parameters). The first parameter is the index from which to start the removal, the second the amount of removed values (if not informed, will remove all values from the index beginning to the end of the array), and from the third onwards will be new values that will enter the place of the values removed. Logo:

    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 it with other values if this is requested.

Slice

The slice has 3% difference of splice . The first and most important is that it does not change the original array, it only returns an array with the captured values. Logo:

    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 rather the index where you should stop capturing, not included. That is, by passing 1, 3 to slice , we get indexes 1 and 2, since 3 is not included. It will also remove all values from the array until the end if it is not informed. The third difference is that slice does not accept more than two parameters, unlike splice , so it does not replace anything in the original array.

About use cases, it depends what you want to do. I think with the explanation of how each one works, give an idea.

External links for more information:

Array.prototype.splice ()

Array.prototype.slice ()

    
19.11.2018 / 18:01
3

In Javascript, confusing slice with splice , or vice versa, is a common mistake. These two functions, despite having similar names, perform two completely different actions.

The first difference is that the slice method does not modify the array itself invoking the splice method.

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

While Splice (verb sew) has syntax array.splice(índiceInicio , quantidadeExcluídos[, item1[,item2[,... itemN]]]) . The first of the two required 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 provide data elements that must be entered into the array in place of the removed items. Each additional item can have any Javascript data type. In fact. specifying zero in the second parameter, you can use splice to insert one or more items in any position of the array

Playing 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>

Splice Examples

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);
    
19.11.2018 / 19:13