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,193
  • 2
  • 10
  • 28
  • You can use `slice()` https://stackoverflow.com/questions/37601282/javascript-array-splice-vs-slice – Armel Jan 03 '19 at 14:18

5 Answers5

9

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
  • 351,820
  • 24
  • 303
  • 358
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
  • 34,173
  • 19
  • 88
  • 85
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,747
  • 4
  • 26
  • 40
0

Use Array.slice:

let arr = [0,1,2,3]
arr.slice(-2); // = [2,3]
arr; // = [0,1,2,3]
Nino Filiu
  • 12,893
  • 9
  • 48
  • 65
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
  • 19