how to use splice to remove element from array code example

Example 1: array remove index from array

const array = [2, 5, 9];

//Get index of the number 5
const index = array.indexOf(5);
//Only splice if the index exists
if (index > -1) {
  //Splice the array
  array.splice(index, 1);
}

//array = [2, 9]
console.log(array);

Example 2: remove elemtns from an array with splice

var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
  fruits.splice(2, 2);
  document.getElementById("demo").innerHTML = fruits;
}

Example 3: splice from array javascript to remove

let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1) 

// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]

Example 4: remove element from array javascript

let numbers = [1,2,3,4]

// to remove last element
let last_num = numbers.pop();
// numbers will now be [1,2,3]

// to remove first element
let first_num = numbers.shift();
//numbers will now be [2,3]

// to remove at an index
let number_index = 1
let index_num = numbers.splice(number_index,1); //removes 1 element at index 1
//numbers will now be [2]

//these methods will modify the numbers array and return the removed element

Tags:

C Example