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])
  }
  }
}

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

Ok so I’m thinking slice()?

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

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.