Array.splice does not work as expected

Asked

Viewed 544 times

2

For example:

var frutas = ["goiaba", "manga", "laranja", "abacate"];
frutas.splice(1, 1);

This code, instead of removing 1 item from the second index of my array (1), only returns the item I want to delete, which in this case is "orange";

That is, instead of returning ["goiaba", "manga", "abacate"] - he returns ["laranja"];

From what I understood in what I read/researched about, the Array.prototype.splice() serves to do what I’m trying there. Am I right? If so, why this method behavior splice?

NOTE: browser Google Chrome version 60

  • 2

    For documentation on MDN on the return of the function: "A list containing the removed elements.". It seems you’ve got it all wrong.

  • 1

    Do this where @Andersoncarloswoss said and removes the element from the array. If you see the contents of your fruit array it will be ["goiaba", "laranja", "abacate"] as expected.

  • Now I get it... I thought splice would return a new Array without the item being removed. Thank you both so much.

  • I must remove the question?

1 answer

3


The method splice is a general purpose method for inserting elements into an array, removing elements from an array, or performing both operations at the same time.

The first argument of splice specifies the position of the array in which the insertion or deletion should begin.

The second argument specifies the number of elements to be excluded.

The first two arguments of splice specify which elements of the array should be deleted. These arguments can be followed by any number of additional arguments, specifying the elements to be inserted into the array, starting at the position specified by the first argument.

See how it works:

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

Now notice this example:

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

Plus this one

var numeros = [1, 2, 3, 4, 5];
var add = numeros.splice(2,2,"a","b","c","[123asd]");

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

  • I was confused by your answer.

  • @durtto, you will understand better if you study the fundamentals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Browser other questions tagged

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