Remove values from a given range and return the array

Viewed 80

I want to remove a range of elements from an array

Let's assume I have an array with given values

let arr = [33,44,56,88,332,67,88,33]

I gave a range as an input let's say from index 3 to index 6. The output I want: [33,44,56,33]

2 Answers

Using Array.prototype.slice and Array.prototype.concat

const 
  arr = [33, 44, 56, 88, 332, 67, 88, 33],
  startIndex = 3,
  endIndex = 6,
  newArr = arr.slice(0, startIndex).concat(arr.slice(endIndex + 1));

console.log(newArr);

Using Array.prototype.slice and spread (...)

const 
  arr = [33, 44, 56, 88, 332, 67, 88, 33],
  startIndex = 3,
  endIndex = 6,
  newArr = [...arr.slice(0, startIndex), ...arr.slice(endIndex + 1)];

console.log(newArr);

Using Array.prototype.splice

Note: splice alters the original array.

const 
  arr = [33, 44, 56, 88, 332, 67, 88, 33],
  startIndex = 3,
  endIndex = 6;
arr.splice(startIndex, endIndex - startIndex + 1);

console.log(arr);

For explicitly removing an array element you can do this:

let arr = [ 33, 44, 56, 88, 332, 67, 88, 33 ];
delete arr [ 3 ]; // the array length doesn't change!
console.log( arr );

To remove a range in an array, you could try this:

let startIndex = 3;
let stopIndex = 6;
let lengthToRemove = (stopIndex + 1) - startIndex;

let arr = [ 33, 44, 56, 88, 332, 67, 88, 33 ];
arr.splice( startIndex, lengthToRemove );
console.log( arr );

Related