Sylar
Sylar

Reputation: 12072

How to remove the first few and last few elements in an array and keep the remainder

Been looking at arr.splice() but that does not seem to be what I'm after. Basically, I need to "splice" a range, ie:

let arr = [1,2,3,4,5,6,7,8,9,10];

I need to return a new array with either:

const newA = [1,2,3]
const newB = [4,5,6]
const newC = [7,8,9]

Surely arr.splice() can achieve the first and last but how to achieve something like newB?

In plain english, "remove the first n index and also the n last index in the array (arr) and give me the rest" which should be newB.

Upvotes: 1

Views: 639

Answers (3)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Yopu want slice not splice (if you want to do it in a single call).

console.log([1,2,3,4,5,6,7,8,9,10].slice(3, 6));

Also, slice returns a new array, splice just changes the original.


To clear up any ambiguity..

If you want to remove the last n items and the first y items, you might consider defining this function..

var a = [1,2,3,4,5,6,7,8,9,10];
const newA = arrayTrim(a, 0, 7);
const newB = arrayTrim(a, 3, 4)
const newC = arrayTrim(a, 6, 1);

console.log(newA, newB, newC);

function arrayTrim(array, first=0, last=0){
  last = !last ? undefined : -last;
  return array.slice(first, last)
}

If you want to start at the nth index and get y items from the array you can use this..

var a = [1,2,3,4,5,6,7,8,9,10];
const newA = arrayTrim(a, 0, 3);
const newB = arrayTrim(a, 3, 3)
const newC = arrayTrim(a, 6, 3)

console.log(newA, newB, newC);

function arrayTrim(array, first, length){
  return array.slice(first, length+first)
}

Upvotes: 4

Thatalent
Thatalent

Reputation: 424

You want to use two arguments for arr.slice

let arr = [1,2,3,4,5,6,7,8,9,10];

arr.slice(0,3); /*returns [1,2,3]*/
arr.slice(3,7); /*returns [4,5,6,7]*/
arr.slice(7,10); /*returns [8,9,10]*/

Upvotes: 1

guest271314
guest271314

Reputation: 1

arr.splice(0, 3);
arr.splice(-4); // or arr.splice(6)
console.log(arr);

Upvotes: 3

Related Questions