最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extracting last n elements from array without disturbing original array - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Jan 3, 2019 at 14:14 Gracie williamsGracie williams 1,1452 gold badges22 silver badges62 bronze badges 1
  • You can use slice() stackoverflow.com/questions/37601282/… – Pingolin Commented Jan 3, 2019 at 14:18
Add a comment  | 

5 Answers 5

Reset to default 13

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]);
发布评论

评论列表(0)

  1. 暂无评论