Problem overview
The method firstN receives an array of integers nums and a number n. It returns a new array with the first n numbers of nums, in the same order. When n is 0 the result is an empty array. The constraints say nums has 1 to 10 numbers and n is between 0 and the length of nums, so n never asks for more numbers than exist.
Three examples show the range of cases:
nums = [3, 8, 1, 9, 4]andn = 3gives[3, 8, 1]. The 9 and the 4 are left out.nums = [5, 6, 7]andn = 0gives[]. No numbers are taken.nums = [2, 4]andn = 2gives[2, 4]. Herenequals the length, so every number is kept.
Approach
You could build the result by hand: make an empty array, loop n times and push nums[i] each time. That works, but JavaScript already has a method for copying a part of an array. slice(start, end) copies the items from index start up to, but not including, index end, into a new array.
Because the end is left out, nums.slice(0, n) copies the items at indexes 0 to n - 1. That is exactly n items, the first n. The start is 0 because we begin at the front.
Step by step
- Copy
numsfrom index 0 up to indexnwithslice, and store the copy in a variable namedresult, declared withlet. - Return
result.
The edge cases need no extra code. With n = 0 the start and end are both 0, so the range is empty and slice returns []. With n equal to the length, the copy runs through the last item and returns every number.
The solution in JavaScript
class Solution {
firstN(nums, n) {
let result = nums.slice(0, n);
return result;
}
}
Details worth knowing
The result is a new array, so the caller's nums stays as it was. Pushing a new number onto the result does not touch the original: with nums = [3, 8, 1, 9, 4], a result of [3, 8, 1] that gets a 0 pushed becomes [3, 8, 1, 0], while nums is still [3, 8, 1, 9, 4].
The method returns the array itself, not text, and numbers stay numbers. If you print the arrays in your own file with console.log, they show as [ 3, 8, 1 ]. The lesson's tests compare the values.
Testing
Running the method on the three examples gives these results:
[ 3, 8, 1 ]
[]
[ 2, 4 ]
Also try n equal to 1, which should give an array with only the first number, and an array with one number and n = 1, which should give that same single number back.
Edge cases and common mistakes
- Off by one with the end index. The end of
sliceis not included.nums.slice(0, n - 1)returns one number too few, andnums.slice(0, n + 1)returns one too many when there are enough numbers. - Using splice.
nums.splice(0, n)also returns the first n numbers, but it removes them fromnums. Useslicewhen the original must stay. - Forgetting to return. A method without a
returngives backundefined, so the tests would see no array. - Special-casing zero. An
if (n === 0)branch is not needed. The empty range already gives an empty array.
