splice javascript remove element code example

Example 1: remove one element using splice

fruits = ['Banana', 'Orange', 'Apple', 'Mango'];

removeFruitByIndex(index: number) {
  this.fruits = [
    ...this.fruits.slice(0, i),
    ...this.fruits.slice(i + 1, this.fruits.length),
  ];
}


removeFruitByValue(fruite: string) {
  const i = this.descriptionsList.indexOf(fruite);
  this.fruits = [
    ...this.fruits.slice(0, i),
    ...this.fruits.slice(i + 1, this.fruits.length),
  ];
}

Example 2: remove 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

Example 3: splice method js

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
//insert new element into array at index 2
let removed = myFish.splice(2, 0, 'drum')

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

Example 4: 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"]