1

Am trying to get last 2 items from an array

result.forEach(function (re) {

console.log(re.files)
// prints ["utilities.rb", "print_utilities.rb", "lities.rb", "agination.rb"]
});

i only want to last two elements in the array in the order

 [ "agination.rb", "print_utilities.rb"]

How it is possible

gvee
  • 16,080
  • 30
  • 47
Sush
  • 1,349
  • 8
  • 22
  • 49

3 Answers3

4

Use the Array.prototype.slice method for this with a negative index.

From MDN:

As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

slice returns a new array, so you can store the result in a new variable.

So in your case, simply use:

var arrayWithLast2Items = re.files.slice(-2);
thomaux
  • 18,290
  • 9
  • 74
  • 97
0

jquery provides a slice method for this

e.g

$([1,2,3]).slice(-2)

https://api.jquery.com/slice/

io2
  • 131
  • 3
-1

Have a temp array with size 2, iterate the elements of original array and over write/copy elements to the temp array. Once iteration is complete, the temp array will contain last 2 elements of original array.

Vinod Jayachandran
  • 3,478
  • 6
  • 37
  • 76