Menu Home

Array.splice()

Hi everyone, and welcome to another sleepy-head edition of Boring JavaScript. Today, we tackle the Array.splice() method. Just like an editor will cut frames from a motion picture by ‘splicing’ the film, we can do the same thing with Arrays merely by – well – ‘splicing’ the array. And as a bonus, we can also insert new entries in at the same time. Let’s see how that works.

Don’t like to read? Then watch our video.

Frankly, my dear, I don’t give a Splice.

The primary purpose of Array.splice is to remove items from an array. It can also be used to add or insert items into the array, and well get to that next.

Array.splice() takes three arguments, with only the first one being required. The first argument specifies the starting index of the array from which to start removing items. The second argument is the number of items to remove. Let’s take a look:

const animals = [
	{ "type": "Cat", "name": "Fluffy", "class": "Mammalia" },
	{ "type": "Dog", "name": "Fido", "class": "Mammalia"},
	{ "type": "Horse", "name": "Mr. Ed", "class": "Mammalia"},
	{ "type": "Cow", "name": "Betsy", "class": "Mammalia"},
	{ "type": "Coyote", "name": "Wile E.", "class": "Mammalia"},
	{ "type": "Road Runner", "name": "Beep Beep", "class": "Aves"},
	{ "type": "Dolphin", "name": "Flipper",  "class": "Mammalia"},
	{ "type": "Whale", "name": "Moby Dick", "class": "Mammalia"},
	{ "type": "Lizard", "name": "Larry", "class": "Reptilia"}
]

console.log('\nBEFORE');
console.log(animals);
const cow = animals.findIndex( animal => animal.type === "Cow" );
animals.splice(cow, 1);
console.log('\nAFTER');
console.log(animals);

Line 16 contains the Array.splice() method. In this case, we are starting with the index represented by the variable “cow” (determined using the findIndex() method in Line 15), and are deleting 1 item. This will delete the item at the index “cow” (which is index #3), and thus delete the entry “Cow” from the array.

// output
BEFORE
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Cow', name: 'Betsy', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

AFTER
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

As you can see, the entry “Cow” is now removed from the animals array

Head ’em up, move ’em out.

What if the second argument is greater than 1? Then starting with the index specified in the first argument, the second argument number of entries will be removed, one after another. But they are not gone forever. When splice() finishes splicing up your array, it will not only mutate your original array, but it will also return in another array the deleted items.

If we take our original code and replace the Array.splice() with this:

console.log('\nBEFORE');
console.log(animals);
const deletedAnimals = animals.splice(1, animals.length - 2);
console.log('\nAFTER');
console.log(animals);
console.log('\nDELETED ANIMALS');
console.log(deletedAnimals);

Not only will our original array be down to only two entries (the first one “Cat” and the last one “Lizard”), but the variable “deletedAnimals” will contain all the entries that were spliced out of the original array. You can see that in the output:

BEFORE
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Cow', name: 'Betsy', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

AFTER
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

DELETED ANIMALS
[
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Cow', name: 'Betsy', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' }
]

Our original animals array is now only two entries big, while “deletedAnimals” contains all the animals removed by the Array.splice() operation.

More Animals, More Trouble

Array.splice() is great at removing items, but it can also be used to insert items into an array. And it’s real easy to do. Let’s look at the following code:

const animals = [
	{ "type": "Cat", "name": "Fluffy", "class": "Mammalia" },
	{ "type": "Dog", "name": "Fido", "class": "Mammalia"},
	{ "type": "Horse", "name": "Mr. Ed", "class": "Mammalia"},
	{ "type": "Road Runner", "name": "Beep Beep", "class": "Aves"},
	{ "type": "Dolphin", "name": "Flipper",  "class": "Mammalia"},
	{ "type": "Whale", "name": "Moby Dick", "class": "Mammalia"},
	{ "type": "Lizard", "name": "Larry", "class": "Reptilia"}
]

const cow = { "type": "Cow", "name": "Betsy", "class": "Mammalia"};
const coyote = { "type": "Coyote", "name": "Wile E.", "class": "Mammalia"};

console.log('\nBEFORE');
console.log(animals);
const horse = animals.findIndex( animal => animal.type === "Horse" );
animals.splice(horse, 0, cow, coyote );
console.log('\nAFTER');
console.log(animals);

Line 17 is the Array.splice(). Notice now that it used three arguments. The first one points to the index in which the splice operation is to commence, the second argument is the number of items to splice out (delete), and all the rest of the arguments are items to be added to the array. In this case, we find the “Horse” entry (Line 16), tell it not to remove any items (second argument is Zero), and then tell JavaScript to insert the “cow” and the “coyote”. Array.splice() will then insert “cow” at index 2, “coyote” at index 3, and “Horse” will move to index 4. Here is the output:

BEFORE
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

AFTER
[
  { type: 'Cat', name: 'Fluffy', class: 'Mammalia' },
  { type: 'Dog', name: 'Fido', class: 'Mammalia' },
  { type: 'Cow', name: 'Betsy', class: 'Mammalia' },
  { type: 'Coyote', name: 'Wile E.', class: 'Mammalia' },
  { type: 'Horse', name: 'Mr. Ed', class: 'Mammalia' },
  { type: 'Road Runner', name: 'Beep Beep', class: 'Aves' },
  { type: 'Dolphin', name: 'Flipper', class: 'Mammalia' },
  { type: 'Whale', name: 'Moby Dick', class: 'Mammalia' },
  { type: 'Lizard', name: 'Larry', class: 'Reptilia' }
]

As you can see, “cow” and “coyote” were inserted just before “Horse”, and “Horse” was moved down on the list.

One more thing: Notice that I have listed “cow” and “coyote” as separate objects. What if you had ten or maybe fifty items. And you don’t know ahead of time what they are. How can you list them out as arguments? JavaScript makes that easy – simply create and array and use the destructuring assignment. Let’s make the follow change in our code:

const newAnimals = [
	{ "type": "Cow", "name": "Betsy", "class": "Mammalia"},
	{ "type": "Coyote", "name": "Wile E.", "class": "Mammalia"}
]
const horse = animals.findIndex( animal => animal.type === "Horse" );
animals.splice(horse, 0, ...newAnimals );

We have now placed “cow” and “coyote” into an array (Lines 1 through 4), then specified the third argument of the Array.splice() method to use the destructuring assignment (Line 6). This will take each entry of the array and pass each as if it was a separate argument to the function. The result? Exactly the same as our original example.

Bonus Video

Just for fun – here is a bonus video on the actual process of ‘film splicing’. As you can tell, it works exactly like Array.splice() – except that it works on film and not arrays.

The video on film splicing

The Video

We also have a video that shows all of our examples above.

Shameless Plug

Check us out everywhere on the Web!

Check out all our videos at: https://www.boringjavascript.com

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: