简体   繁体   中英

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

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; }

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; }

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);

Use Array.slice:

let arr = [0,1,2,3]
arr.slice(-2); // = [2,3]
arr; // = [0,1,2,3]
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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM