1

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]

1
  • A simple for loop? Commented May 30, 2022 at 18:03

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Hey @robni, the only problem with arr.splice(startingPoing, length) i can't give length, as length can be dynamic
So how do you know the length? Did you want to stop at a specific value? Say your range should be start by value 88 and stop by the value 33? Note: the second parameter (lengthToRemove) is the amount of elements to remove from the startingpoint (startingPoint). If you don't know the amount, you need to know when you want to "stop" the splice.
I don't know about the length, the only thing I know is a range, from index 3 to index 6 (3,6) or index 1 to index 4 (1,4) @robni
I edited my answer. The lengthToRemove is now calculated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.