Understanding how to parse an array of arrays in JavaScript can be a

Looking for a function that can extract a value from an array containing multiple arrays? Simply use getValueFromArray(array, [2, 4]) to get the 4th element of the 2d array within the main array.

Check out the code snippet below:

function getValueFromArray(arr, indexes){

var val,
    currentIndex = indexes[0];

    if(!arr[currentIndex] || arr[currentIndex] === '') return value = '';

    indexes.splice(0, 1);

    if(arr[currentIndex].length) 
        getValueFromArray(arr[currentIndex], indexes);
    else {
        val = arr[currentIndex];
        return val;
    }
 }


      var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]); // should return 3

      var x = getValueFromArray([[1,2,3,4], [1,2,3,4], [5,6,7,8]], [2, 3]); // should return 8

      var z = getValueFromArray(
                           [
                               [[1,2,3,4], [1,2,3,4], [1,2,3,4]],
                               [[1,2,3,4], [1,2,3,4]]
                           ], 
                           [0, 1, 2]
                          ); // should return 3

The function correctly returns the expected value when debugged directly. However, while trying to assign it to a variable, it shows undefined. This issue might be due to recursion. Any suggestions on fixing this?

Appreciate your help!

Answer №1

Your recursive results are not being properly returned.

if(arr[currentIndex].length) 
    getValueFromArray(arr[currentIndex], indexes);

This code snippet should be adjusted as follows:

if(arr[currentIndex].length) 
    return getValueFromArray(arr[currentIndex], indexes);

Answer №2

There is a small issue in your code where you forgot to return the result after the if condition. You can try using the following updated code:

function getValueFromArray(arr, indexes){

    var val,
        currentIndex = indexes[0];

        if(!arr[currentIndex] || arr[currentIndex] === '') return value = '';

        indexes.splice(0, 1);

        if(arr[currentIndex].length) 
           return getValueFromArray(arr[currentIndex], indexes);
        else {
            val = arr[currentIndex];
            return val;
        }
     }
    var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]);
    console.log(y)

After running this code, you will see that the result is now correctly stored in the variable.

Answer №3

It is advisable to insert a return statement before calling getValueFromArray(arr[currentIndex], indexes);
This will allow the final calculated value to travel up through the recursive method call stack as each recursive call returns.

Answer №4

Your answer is spot on. All you needed to do was make sure to include the return statement for the recursive call:

if(arr[currentIndex].length) 
    getValueFromArray(arr[currentIndex], indexes); // <---- here

However, it's worth noting that there is a more concise way to achieve the same result (although this may impact the integrity of the original indexes array):

function getValueFromArray(arr, indexes){
  while(indexes.length) arr=arr[indexes.shift()]
  return arr
}

Answer №5

The reason for the issue is that the condition is not returning any value. Try using the code below

function getValueFromArray(arr, indexes){

var val='',currentIndex = indexes[0];

    if(!arr[currentIndex] || arr[currentIndex] === '') return val;

    indexes.splice(0, 1);

    if(arr[currentIndex].length) {

       // The problem occurs when the function does not encounter a 'return' statement 
       // and ends up returning nothing.
        return getValueFromArray(arr[currentIndex], indexes);
    }   
    else { 
        val = arr[currentIndex];
        return val;
    }
 }

Afterwards, you can log the variable to the console

var y = getValueFromArray([[1,2,3,4], [1,2,3,4]], [0, 2]);
console.log(y)

Answer №6

I also wanted to share my code because it offers a more straightforward approach to solving the problem at hand.
This solution avoids recursion, potentially resulting in quicker execution.

var arr = [
  [
    [
      [12, 5, 6],
      [ 6, 7, 8],
      [11, 0, 9]
    ],
    [
      [-1, 1, 8],
      [ 4, 5, 6]
    ]
  ],
  [
    [
        [7, 8, 9, 10]
    ]
  ]
];

function getValueFromArray(arr, indexes){
    var value = arr, i = 0, len = indexes.length, index = null;

    for (; i < len; i += 1) {
        index = indexes[i];
        // check if the current array contains an {index}-th record
        if ( index in value ) { 
            value = value[index];
        } else {
            // or throw an exception if you want
            return null;
        }
    }

    return value;
 }

getValueFromArray(arr, [0, 1, 1, 2]) // 6

Answer №7

function extractValue(arr, indexes) {
    // Check if the input is valid
    // Exit if arr is not an array or empty
    // Exit if indexes is not an array or empty
    if (!Array.isArray(arr) || !arr.length || !Array.isArray(indexes) || !indexes.length) {
        return; // Handle this case accordingly
    }
    var currentIndex = indexes.shift();
    // Check for valid index
    // Exit if index is out of bounds or negative
    if (arr.length <= currentIndex || currentIndex < 0) {
        return; // Handle this case accordingly
    }
    return Array.isArray(arr[currentIndex]) ? extractValue(arr[currentIndex], indexes) : arr[currentIndex];
}

Answer №8

Stop overcomplicating things:

function getValueFromArray(arr, indexes){
    return arr[indexes[0]][indexes[1]];
}

Simplified version for 1 to 3 dimensional arrays:

function getValueFromArray(arr, indexes){
    if (indexes.length == 1) {
        return arr[indexes[0]];
    } else if (indexes.length == 2) {
        return arr[indexes[0][indexes[1]];
    } else if (indexes.length == 3) {
        return arr[indexes[0][indexes[1][indexes[2]];
    } else {
      // What about 4 dimensional arrays?
    }
}

Do you really need more than a 3 dimensional array?

Perhaps there's a way to iterate with indexes[i], but it's eluding me at the moment and might not even be feasible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

webpack is failing to load SVG files

My application structure includes: /webapp /lib /assets ic_add_black_24px.svg ic_clear_black_24px.svg .. .. The configuration in my webpack.config.js looks like this: var path = require('path'), webpack = requ ...

Obtain a collection of the corresponding keys for a given value from dictionaries

I'm implementing a function that retrieves a list of keys associated with a specific value in the dictionary. Although I am able to print out the first key successfully, I'm facing difficulties in displaying subsequent keys. I understand that I ...

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

Running the Npm start command encounters an error

My terminal is showing the following error message: Q:\clone\node-cloudinary-instagram\node_modules\express\lib\router\route.js:202 throw new Error(msg); Error: Route.get() requires a callback function but go ...

JQuery Ajax request functioning smoothly while native JavaScript falls short

I am currently troubleshooting two AJAX calls. One is written in native JavaScript while the other utilizes JQuery to call a PHP script. The jQuery AJAX call seems to be functioning properly, but I am encountering issues with the JavaScript version. Here i ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Generating a primary XML element encompassing multiple namespaces

I am currently working on integrating Restful services with Backbone.js framework. In this project, I need to send XML data and add multiple namespaces to it. Here is the snippet of my current JavaScript code: var mainNamespace = "xmlns='http://serv ...

Integrating a conditional statement into the existing for loop code to conceal the covers

My goal is to hide the covers after they are clicked using an if statement within the for loop code. I believe this is where it should be placed. Trying to prevent this action from happening. I made an attempt at achieving this but unfortunately couldn&a ...

Vue allows you to easily generate child div elements within a parent

Having some issues creating a child div with Vue. The code is being placed correctly, but it's being stored as an array. <template> <div class="containers" v-bind:style="{ backgroundColor: pageStyle.backgroundColor, paddingLeft:'5%& ...

Utilize the 'response.download' method to retrieve unique data not typically expected for a given request

Each time I try to download a file, the response I get is different. The file is generated correctly every time: user,first_name,last_name,active,completed_training 4,Foo,Bas,YES,YES 5,Ble,Loco,NO,NO 9,gui2,md,NO,NO 3137,foo,baz,NO,NO However, the respons ...

Searching an array through sequential iteration

Seeking assistance urgently this week. My professor is not providing clear explanations. The Issue: I need to import a file and search for a specific data requested by a user. The output should display something like: ...

Utilize Jquery to transform 3 arrays into separate objects distinguished by unique IDs

Recently, I've been experimenting with a very simplistic jquery admin area menu. My goal is to have jQuery create 3 identical menus with different IDs. I was able to accomplish this by creating a function and calling it three times with various variab ...

the ReactJS data length is accessible when saving changes, but not when refreshing the browser

I am facing a puzzling issue with my API data in this React component. When I console.log the array of 10 objects from the API, everything seems fine. However, when I try to access "data.data.length" and save the file, it works without any errors displayin ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

Troubleshooting a problem with the skybox texture in Three.js

I am currently experimenting with creating a basic Skybox using Three.js, but I've encountered an issue where the texture I'm applying to the cube is only visible on the outside and not on the inside. Below is the code for my skybox: const path ...

Differences between JavaScript closures and traditional functions

Recently, I came across an example of JavaScript closure that left me puzzled. The example code is as follows: function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); ...

Dart and external CSS and JS libraries and tools

As I prepare to dive into developing my very first web application, one technology that has caught my eye is Google Dart. The idea of using a new, innovative approach to web development excites me, and I am seriously considering utilizing it for my project ...