Home > Back-end >  Remove values from a given range and return the array
Remove values from a given range and return the array

Time:05-31

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]

CodePudding user response:

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);

CodePudding user response:

For explicitly removing an array element you can do this:

delete arr [ 3 ];

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