Sup3r D
Sup3r D

Reputation: 147

Returning first n elements of an array Javascript

I am writing a function that will return the first n elements of an array and if n is undefined then return the first element.

*Edit: I solved the problem.

_.first = function(array, n) {
var result = [];
if (n == undefined) {
  return array[0];
}
var m;
if (array.length < n) {
  m = array.length;
} else {
  m = n;
}
  for (var i = 0; i < m; i++) {
  result.push(array[i]);
} return result;
};

Upvotes: 2

Views: 7348

Answers (3)

Cyan Coder
Cyan Coder

Reputation: 87

Basic is

const newArr = function(arr) {return n }

Shorthand

const newArr = arr => { return n}

Upvotes: 0

Zuraiz Zafar
Zuraiz Zafar

Reputation: 11

1_.first = function(array, n) {
2 var result = [];
3 for (var i = 0; i < n; i++) {
4   result.push(array[i]);
5   return result;
6 } return array[0];
7};

the problem is on the 5th line, you seem to be returning the first and not taking into account the n parts

a solution might be

_first = function(array, n){
 var result = [];
 if(n === undefined) return array[0];
 for (var i = 0; i < n; i++) {
   result.push(array[i]);
 } 
 return result;
}

Upvotes: 0

C.Unbay
C.Unbay

Reputation: 2826

This program is basically checking if the n value is bigger than the array's length, if it is, then it exits.

If n is not a number it exits. If it is it executes the program and logs the values of indexes with for loop until i reaches the n value. Also, it pushes the values to the empty array, so you can get the values from the array for later use.

var arr1 = [2, 3, 4, 5, 6, 7, 8];
var arr2 = []; //empty array    

function arrNreturn(arr, n){
  if(typeof n != 'number'){
    console.log('n is not a number');
    return false; //exit the program
  }
  if(n > arr.length){
    console.log("the n value is bigger than the length");
  }else{
    for(var i = 0; i < n; i++){
      console.log(arr[n]);
      arr2.push(arr[n]);
    }
  }
}

arrNreturn(arr1, 10);

Upvotes: 1

Related Questions