Published on

Playing Around with JavaScript Arrays Slice Method

Authors

Today I had to work out how to get the top n and bottom n elements of 2 different lists in JavaScript.

Luckily doing this is really easy.

Say I have an array defined as below (the ordering of the array is irrelevant to the method used to get the top and bottom n):

const myNums = [1, 2, 3, 4]

Getting the Top N Elements of an Array

To get the top 2 elements you use slice as below:

console.log(myNums.slice(0, 2))

Which outputs:

;[1, 2]

Getting the Bottom N Elements of an Array

Getting the bottom 2 elements can be done as below:

console.log(myNums.slice(-2))

Which outputs:

;[3, 4]

What if my slice parameters are too big or small

In both cases you do not have to worry about the number being too big or too small.

In the top case it will simply return the whole list for example:

console.log(myNums.slice(0, 20))

Returns:

;[1, 2, 3, 4]

Similarly having a really small negative will also return the whole list:

console.log(myNums.slice(-20))
;[1, 2, 3, 4]

Other Interesting Ways to Use Slice

I played around with slice a bit more to see what happens if I fiddle with the parameters.

Empty Slice

In case you were curious an empty slice... you guessed it returns the whole list!

console.log(myNums.slice())
;[1, 2, 3, 4]

Start Index and Really Small Negative End Parameter

And if you put the start index with a really small negative as the second parameter you get an empty list:

console.log(myNums.slice(0, -200))
;[]

Cutting Off the Last N Items

You can also conveniently cut off just the last n items of a list as follows:

console.log(myNums.slice(0, -2))
;[1, 2]

Cutting of the First N Items

If you provide only the first parameter and it is not negative think of it as slice the first n elements off the array for example to remove the first 2 elements:

console.log(myNums.slice(2))
;[3, 4]

Start Parameter is Bigger Than End Parameter

If you flip the method parameters around by mistake:

console.log(myNums.slice(2, 0))

You get the empty array:

;[]