This page looks best with JavaScript enabled

Access an array in reverse in Javascript

 ·   ·  ☕ 2 min read

Access an array in reverse.

Consider the array in the code block below -

1
const nums = [1, 2, 3];

Accessing the array is easy enough.

1
2
3
4
console.log(nums[0]);
console.log(nums[1]);
console.log(nums[2]);
/* 1 2 3 */

But, what if you want to access the array from the last element?

Use pop

We have seen one of the ways to do that using pop.

1
2
3
4
console.log(nums.pop());
console.log(nums.pop());
console.log(nums.pop());
/* 3 2 1 */

But, this changes the array.

1
2
console.log(nums);
// []

Use slice

If you want to just access the array from the last element, but not change the array -

1
2
3
4
console.log(nums.slice(-1, 3));
console.log(nums.slice(-2, 2));
console.log(nums.slice(-3, 1));
// [3] [2] [1]

Or..

1
2
3
4
console.log(nums.slice(-1, nums.length));
console.log(nums.slice(-2, nums.length - 1));
console.log(nums.slice(-3, nums.length - 2));
// [3] [2] [1]

To reverse parts of the array or the whole of it -

1
2
3
4
5
console.log(nums.slice(-1));
console.log(nums.slice(-2));
console.log(nums.slice(-3));

// [ 3 ] [ 2, 3 ] [ 1, 2, 3 ]

Use reverse

Instead of accessing the array from the reverse, make reverse the new forward.

1
2
3
4
5
6
7
const nums = [1, 2, 3];

const numsRv = nums.reverse();
console.log(numsRv[0]);
console.log(numsRv[1]);
console.log(numsRv[2]);
// 3 2 1

To retain the original array..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const nums = [1, 2, 3];

const numsRv = nums.slice().reverse();
console.log(numsRv[0]);
console.log(numsRv[1]);
console.log(numsRv[2]);
// 3 2 1

console.log(nums);
// [1, 2, 3]

Which options should I choose?

What you choose really depends on what you want to do with the result and with the original array. I would personally use a pop on an array clone to make the code look squeaky clean and run a bit faster.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const nums = [1, 2, 3];

const numsCp = nums.slice();
console.log(numsCp.pop());
console.log(numsCp.pop());
console.log(numsCp.pop());
// 3 2 1

console.log(nums);
// [ 1, 2, 3 ]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things