Wanna see something cool? Check out Angular Spotify 🎧

Get the last items of an array using array.slice()

Usage

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.

The original array will not be modified.

See some of the common usage as below

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array.slice()     // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array.slice(0, 2) // [0, 1]
array.slice(1, 4) // [1, 2, 3]

Slice negative

But I never knew the slice method takes negative integers for the start and end index. It’s a great way of getting the last items of an array.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
array.slice(-1)     // [9]
array.slice(-2, -1) // [8]
array.slice(-3, -1) // [7, 8]
array.slice(-1, -3) // [] Because -1 > -3, so it is like you do array.slice(3, 1) where start is greater than end

See more

Where else than MDN 🤣

Published 3 Nov 2020

Read more

 — Angular Jira Clone Part 07 - Build a rich text editor
 — How to iterate over objects in TypeScript
 — How to copy an object from the Chrome inspector console as code
 — Use async functions instead of callbacks for asynchronous code
 — The different between type and interface in TypeScript

Follow @trungvose on Twitter for more!