Assume we have the following array and we want to remove Robert from the array:
const names = ['Peter', 'John', 'Sally', 'Robert', 'Laila'];
const index = 3;
const newNames = [...names.slice(0, index), ...names.slice(index + 1)];
console.log(newNames);
What we are doing with the newNames array is creating a new array composed of two parts:
-
names.slice(0, index)- Return thenamesarray with elements from 0 to index-1. -
names.slice(index + 1)- Return thenamesarray with elements from index+1 to the end of the names array.
Taking 1 and 2 above, we then use the spread operator in order to have both results in the new array. The new array is then: ['Peter', 'John', 'Sally', 'Laila'].
If we didn’t know the index of Robert in the array, we can use the indexOf() function as follows:
const index = names.indexOf('Robert');