2

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,732
  • 35
  • 50
Sush
  • 1,449
  • 8
  • 26
  • 51

3 Answers3

5

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
  • 19,133
  • 10
  • 76
  • 103
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,726
  • 8
  • 51
  • 88