Remove an element from an array at the specified index

Last Updated On Friday 21st Jan 2022

Function to remove an element from an array at the specified index.

  • The Array.prototype.slice() method returns a subset of the array.
  • It slices the Array into two parts that do not have the element at a specific index in it.
	const names = ["John", "Philips", "Usian", "Brady", "Colt", "Jesse"];
	

The Below Code returns the new Array.

Example 1

	const removeElementAt = (arr, i) =>
    (i || i === 0) ?
    [...arr.slice(0, i), ...arr.slice(i + 1)] :
    arr;

const newArr = removeElementAt(names, 1);
console.log(names)
console.log(newArr)
	
	// [ 'John', 'Philips', 'Usian', 'Brady', 'Colt', 'Jesse' ]
// [ 'John', 'Usian', 'Brady', 'Colt', 'Jesse' ]
	
  • For mutating, you can simply use the Array.prototype.splice() method.
  • The Below Code mutates the original Array

Example 2

	const removeElementAt = (arr, i, mutate = false) =>
  (i || i === 0)
    ? mutate
      ? arr.splice(i, 1) && arr
      : [...arr.slice(0, i), ...arr.slice(i + 1)]
    : arr;
	
  • By Adding the mutate=true , you can mutate the original array.
	const newArr = removeElementAt(names, 3, true);
console.log(names)
console.log(newArr)
	
	// [ 'John', 'Philips', 'Usian', 'Colt', 'Jesse' ]
// [ 'John', 'Philips', 'Usian', 'Colt', 'Jesse' ]