Wilhelm Michaelsen
Wilhelm Michaelsen

Reputation: 663

Move all elements in array after removing one with splice - JavaScript

I have an array of objects each containing a name and adress. If I remove en element in this array (an object) with splice(), are the other elements moved "down" in the array so that no blanks are left in the array. If not how can you move all elements down one index in the array?

people is another array containing strings of names

My array looks like this:

var array = [0];

for (int i = 0; i < people.length; i++)
{
    array.push({
        name: people[i],
        adress: "adress"
    });
}

How I remove

for (int i = 0; i < array.length; i++)
{
    if (array[i].name == "some name")
    {
        array.splice(i, 1);
    }
}

Will this leave the array with a blank index somewhere in it, or are the other elements moved when splice()is called. I have looked over the documentation but I can't find an answer to this.

Upvotes: 0

Views: 1724

Answers (1)

Shawn Erquhart
Shawn Erquhart

Reputation: 1858

Here's how you find out the answer for this:

console.log(array);

for (int i = 0; i < array.length; i++)
{
  if (array[i].name == "some name")
    {
      array.splice(i, 1);
  }
}

console.log(array);

Check out the console log before and after the for loop to see what happened. Playing with live code is the best possible way to learn.

Lastly, as stated in my comment, MDN's docs are exhaustive - you can always reference them if you're unsure what something does in JS. Here's the article pertinent to your question - documentation for Array.prototype.slice():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Upvotes: 1

Related Questions