skip to Main Content

javascript multidimensional Array get first array last elment,second array second element and 3 array first element
input array=[[1,2,3],[4,5,6],[7,8,9]];
output= [3,5,7];

how to get output with loop in multidimensional array

3

Answers


  1. To get the specific elements from your multidimensional array using a loop in JavaScript, you can access the elements by specifying their indices. Here’s how you can do it:

    const inputArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    const output = [];
    
    for (let i = 0; i < inputArray.length; i++) {
        if (i === 0) {
            // Get the last element of the first array
            output.push(inputArray[i][inputArray[i].length - 1]);
        } else if (i === 1) {
            // Get the second element of the second array
            output.push(inputArray[i][1]);
        } else if (i === 2) {
            // Get the first element of the third array
            output.push(inputArray[i][0]);
        }
    }
    
    console.log(output); // Output: [3, 5, 7]
    

    Explanation:

    • We loop through the outer array using a for loop.
    • For each iteration, we check which array we are in (using the index i):
      • If i is 0, we push the last element of the first array (inputArray[0][inputArray[0].length - 1]).
      • If i is 1, we push the second element of the second array (inputArray[1][1]).
      • If i is 2, we push the first element of the third array (inputArray[2][0]).

    This gives you the desired output: [3, 5, 7].

    This answer could definitely be made to be more scalable, but I wasn’t sure if you wanted it to be more dynamic or just to fit this specific case.

    Login or Signup to reply.
  2. You could try to loop with 2 indexes:

    const input = [[1,2,3],[4,5,6],[7,8,9]];
    
    let i = input[0].length, n = 0;
    const result = [];
    while(i--){
      result.push(input[n++][i]);
    }
    
    console.log(result);
    Login or Signup to reply.
  3. You could try to loop with 2 indexes:

    const
      input  = [[1,2,3],[4,5,6],[7,8,9]]
    , result = []
      ;
    for (let p=input.length, i=0; p--; i++)
      result.push(input[i][p]);
      
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search