Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - splice()

https://www.w3schools.com/jsref/jsref_obj_array.asp

The splice() method can be used to add new items to an array. It can also be used to remove items from an array. The splice() method take three or more arguments:

  • The first parameter defines the position where new elements should be added (spliced in).
  • The second parameter defines how many elements should be removed.
  • The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

 


// the original array.
let fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("before").innerHTML = fruits.join("*");

// will add Lemon and Kiwi AFTER Orange. It will then add two new elements to the end of the array.
fruits.splice(2, 0, "Lemon", "Kiwi");

// will now show all six elements.
document.getElementById("after").innerHTML = fruits.join("*");

results:


// demo 1
// Adding items to the beginning of the array.
let fruits2 = ["orange", "banana", "apple", "pineapple"];
fruits2.splice(0, 0, "lemon", "lime");
$("#demo1").html("results: " + fruits.join("-"));

results:


// demo 2
// adding items to the end of the array
let cars = ["ford", "chevy", "nissan", "toyota"];
cars.splice(cars.length, 0, "gmc", "hyundai");
$("#demo2").html("results: " + cars.join("-"));

results:


// demo 3
// adding items to the end of the array and then resorting them
let colors = ["blue", "green", "yellow", "red"];
colors.splice(colors.length, 0, "black", "white");
colors = colors.sort();
$("#demo3").html("results: " + colors.toString());

results:


// demo 4
// removing the first two items
let foods = ["salads", "vegetables", "pizza", "tacos", "pasta", "rice"];
foods.splice(0, 2);
$("#demo4").html("results: " + foods.toString());

results:


// demo 5
// removing the last two items(tom & jerry)
let cartoons = ["ricky", "bobby", "elmer", "bugs", "tom", "jerry"];
cartoons = cartoons.reverse();
cartoons.splice(0, 2);
cartoons = cartoons.reverse();
$("#demo5").html("results: " + cartoons.toString());

results:


// demo 6
// removing an item within the array
let sodas = ["coke", "pepsi", "mt dew", "rat poison", "dr pepper", "sprite"];
let removeIndex = sodas.indexOf("rat poison"); //remove this
if (removeIndex != -1)
{
    // simple. Get the position of the offending item and mark it for removal.
    sodas.splice(removeIndex, 1);
}

sodas = sodas.sort();
$("#demo6").html("results: " + sodas.toString());

results: