Having trouble with this codewars problem

Here is the task: Training on pick a set of first elements | Codewars

I know that I am on the right track, but I don’t know what I am doing wrong ):

function first(arr, n) {
  console.log(arr, n)
  const myArray = [];
  
  
  
  for (let i = 0; i < n; i++) {
    if (n == 0) {
    return myArray;
  } else if (n == undefined) {
    myArray.push(arr[0])
  }
  }
}

If a second argument is not passed to your function, what gets returned?

Better yet, if a second argument is not passed to your function, how does you for loop condition work?

FYI - This problem can be solved in a single line of code inside the function. No for or while loops needed.

Here we go:

function first(arr, n) {
  const myArray = [];
  
  if (n == undefined) {
    myArray.push(arr[0]);
    return myArray;
  }
  
  for (let i = 0; i < n; i++) {
    myArray.push(arr[i]);
  }
  return myArray;
  console.log(myArray);
}

Failing only one test when I click ‘submit’.

Incorrect answer for:
arr=[a,b,c,d,e]
len=10
: expected [ Array(10) ] to have the same ordered members as [ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ ]

If n is larger then amount of elements in arr what values are you going to be pushing to myArray when you hit an index outside of arr?

ok, so if I understand you correctly,

“IF n > arr.length return something”?

Try it out and tell me if that works.

will do!!!

dang it!! ): I guess my brain can’t see what the problem is. the error message literally doesn’t make any sense. How can you put only the first five by default if the length is more than the array? I don’t get it?

function first(arr, n) {
  const myArray = [];
  
  if (n == undefined) {
    myArray.push(arr[0]);
    return myArray;
  }
  
  if (n < arr.length) {
    return []
  } 
  
  for (let i = 0; i < n; i++) {
    myArray.push(arr[i]);
  }
  return myArray;
  console.log(myArray);
}

What key word stuck out to you that told you that a loop wasn’t needed? Just so I can know for future reference

It was not a single word. It was the phrase “get the first element(s) of a sequence”. There is a built-in JavaScript method for getting a sequence of elements of an array. I used that. If you went through the Basic Data Structures portion of the JS curriculum here, then you learned about it.

1 Like

Ok so I’m thinking slice()?

function first(arr, n) {
  if (n == 0) {
    return []
  }
  return arr.slice(0, n)
}

Is this even necessary?

How will you properly handle the case when there is not a second argument passed to the function?

You sure you have the syntax right for if n is larger then arr.length? And would they want an empty array in that case as well?

But the slice method i think is a better way to go overall. The test even gives a little bit of a hint on how to handle n if there is only one argument given.