Gracie williams
Gracie williams

Reputation: 1145

Extracting last n elements from array without disturbing original array

I want to extract last n elements from array without splice

I have array like below , I want to get last 2 or n elements from any array in new array [33, 44]

[22, 55, 77, 88, 99, 22, 33, 44] 

I have tried to copy old array to new array and then do splice.But i believe there must be some other better way.

var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var temp = [];
temp = arr;
temp.splice(-2);

Above code is also removing last 2 elements from original array arr;

So how can i just extract last n elements from original array without disturning it into new variable

Upvotes: 5

Views: 5376

Answers (5)

Hayk Manasyan
Hayk Manasyan

Reputation: 506

var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;
var temp = [];
var arrCount = arr.length;
temp.push(arr[arrCount-1]);
temp.push(arr[arrCount-2]);

Upvotes: -1

Nino Filiu
Nino Filiu

Reputation: 18473

Use Array.slice:

let arr = [0,1,2,3]
arr.slice(-2); // = [2,3]
arr; // = [0,1,2,3]

Upvotes: 0

FK82
FK82

Reputation: 5075

You can create a shallow copy with Array.from and then splice it.

Or just use Array.prototype.slice as suggested by some other answers.

const a = [22, 55, 77, 88, 99, 22, 33, 44];
console.log(Array.from(a).splice(-2));
console.log(a);

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39322

Use slice() instead of splice():

As from Docs:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

var arr = [22, 55, 77, 88, 99, 22, 33, 44] ;

var newArr = arr.slice(-2);

console.log(newArr);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 7

Nina Scholz
Nina Scholz

Reputation: 386540

You could use Array#slice, which does not alter the original array.

var array = [22, 55, 77, 88, 99, 22, 33, 44];
    temp = array.slice(-2);

console.log(temp);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 13

Related Questions