3

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

Gracie williams
  • 1,287
  • 2
  • 16
  • 39
  • You can use `slice()` https://stackoverflow.com/questions/37601282/javascript-array-splice-vs-slice – Pingolin Jan 03 '19 at 14:18

5 Answers5

10

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
6

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; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

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);
FK82
  • 4,907
  • 4
  • 29
  • 42
0

Use Array.slice:

let arr = [0,1,2,3]
arr.slice(-2); // = [2,3]
arr; // = [0,1,2,3]
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
0
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]);
Hayk Manasyan
  • 508
  • 2
  • 20