Home > Back-end >  Get an element from an array at an index a user specified
Get an element from an array at an index a user specified

Time:06-11

I want to build a function that takes two inputs:

  1. an array of arrays
  2. index number

and then returns an array inside the input array that it located at the input index.

The following is the code I got so far.

So, if a user calls the function with the following inputs, the expected result is [4,5,6] .

 const input = [
       [1,2,3],
       [4,5,6],
       [7,8,9]
    ];
    
 const index = 1;

function grab(input, index){
   var result = [];

   return result = input[index];
   console.log(result);
};

CodePudding user response:

const input = [
       [1,2,3],
       [4,5,6],
       [7,8,9]
    ];
    
 const index = 1;

const result= grab(input, index);
console.log(result);

function grab(arr, index){
   return [...input[index]]; // return copy of selected array
   // to return not a copy -> return input[index];
};

CodePudding user response:

function grab(input, index){
   var result = [];

   for(var i=0; i<input.length; i  ){
          result.push(input[index][i]);
       }
       return result;
};

You could learn more about slicing 2-D arrays in javascript from this source: 1

  • Related