user10094650
user10094650

Reputation:

Resize array by index

I got an array like ...

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

..., an start-index let start = 2 and an end-index let end = 5.

I'd like to resize the array starting with index startIndex and ending with endIndex like this example:

start = 2;
end = 3;

let result = [2, 3]

start = 2;
end = 2;

let result = [2]

start = 0;
end = 8;

let result = [0, 1, 2, 3, 4, 5, 6, 7, 8]

This snippet below is what I've got so far. But obviously there are some issues:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let start = 2
let end = 3
array.splice(0, start);
array.splice(end, array.length);

console.log(array)

Upvotes: 0

Views: 390

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take Array#copyWithin and adjust the length of the array.

var start = 2,
    end = 5,
    array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

array.copyWithin(0, start, end + 1).length = end - start + 1;

console.log(array);

Upvotes: 0

Amer_Shaik
Amer_Shaik

Reputation: 3

when you splice result array (array after you splice first time) with the index of the actual array [array in question], you got that output please look at the following code. Run this code and see you will understand

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let start = 2
let end = 3

array.splice(0,start);

//After splice this is result array [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 

console.log(array);

//If you splice again with end=3 index you get the result array as [2, 3, 4]. 
// To get your desired output as array you should work on array after you splice first time

array.splice(2,array.length);

console.log(array);

I hope this explains what happen with your code. As a reminder about splice method. The splice() method adds/removes items to/from an array, and returns the removed item(s).

Syntax:

array.splice(index, howmany, item1, ....., itemX)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192016

You can use Array.slice() to get a new array:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

const start = 2
const end = 3

const result = array.slice(start, end + 1);

console.log(result)

And if you want to mutate the original array directly, you can combine that with Array.splice():

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

const start = 2
const end = 3

array.splice(0, array.length, ...array.slice(start, end + 1));

console.log(array)

Upvotes: 1

Ruzihm
Ruzihm

Reputation: 20259

You can use Array.slice(start,end) and increase end by one, since you want it to be inclusive.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let start = 2
let end = 3
var result = array.slice(start, end+1);

console.log(result)

Upvotes: 1

Related Questions