Wanna see something cool? Check out Angular Spotify 🎧
All Articles

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

Recent Posts

How to iterate over objects in TypeScript

Use let k: keyof T and a for-in loop to iterate objects when you know exactly what the keys will be or Object.entries to iterate over the keys and values of any object.

Angular Jira Clone Part 07 - Build a rich text editor

My seventh tutorial will focus on another kind of text editor - a rich text HTML editor


Follow @tuantrungvo on Twitter for more!