JenMorgan / js-learning

0 stars 0 forks source link

Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array #28

Open kartamyshev opened 4 years ago

kartamyshev commented 4 years ago
console.log(first([7, 9, 0, -2])); // 7
console.log(first([],3)); // []
console.log(first([7, 9, 0, -2],3)); // [7, 9, 0]
console.log(first([7, 9, 0, -2],6)); // [7, 9, 0, -2]
console.log(first([7, 9, 0, -2],-3)); // []
JenMorgan commented 4 years ago
function getTheFirst (arr, n) {
    if (!n) return arr[0];
    return arr.reduce((newArr, current) => (arr.indexOf(current) < n) ? newArr.concat(current) : newArr, []);
}
kartamyshev commented 4 years ago
function getTheFirst (arr, n) {
  if (!n) return arr[0];
  if (n < 0) return [];

  return arr.slice(0, n);
}
kartamyshev commented 4 years ago
function getTheFirst(arr, n) {
  if (!n) return arr[0];

  return arr.filter(current => arr.indexOf(current) < n);
}