Breaking down a multidimensional array into individual arrays using Javascript

Having a serious problem here, I have an array structured like this:

[[0,50],[0,68],[1,26],[2,9],[2,32]]

I am looking to split this array into two separate arrays like so:

array1 = [[0,50][1,0][2,9]]
array2 = [[0,68][1,26][2,32]]

Yes, you are correct guys, I need this in order to create a flot chart.

If anyone is curious about the source of data, this is how it appears in Firebase:

{
  "1433203200000" : {
    "-JpgJnANTpQFprRieImv" : {
      "events" : 5,
      "name" : "Home office",
      "returningVisitors" : 9,
      "totalVisitors" : 50
    },
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "events" : 10,
      "name" : "Samin Place",
      "returningVisitors" : 32,
      "totalVisitors" : 68
    }
  },
  "1433289600000" : {
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "name" : "Samin Place",
      "newVisitors" : 1,
      "returningVisitors" : 25,
      "totalVisitors" : 26
    }
  },
  "1433376000000" : {
    "-JpgJnANTpQFprRieImv" : {
      "events" : 5,
      "name" : "Home office",
      "returningVisitors" : 9,
      "totalVisitors" : 9
    },
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "events" : 10,
      "name" : "Samin Place",
      "returningVisitors" : 32,
      "totalVisitors" : 32
    }
  }
}

The goal is to iterate through each timestamp and each child entry. Within each child entry, there is a "totalVisitors" value that I require for my chart.

BONUS

As noted, the first timestamp has two child entries, which is fine. However, the second timestamp only has one child entry - "-JqsQjFTjHpzKqWgE_KJ." Therefore, I need to add a null value for the missing entry into the new array (in our example, it's the second position in array1).

This is what I refer to as the CHALLENGE :)

Any assistance is greatly appreciated, thank you for your attention.

Edit:

If it helps someone, this is the type of chart that I need

here is link

X-axis - timestamps
Y-axis - totalVisitors value
Lines - each unique timestamp child

Answer №1

Here is a jsfiddle that I have created for you. Can you please review and confirm if this meets your requirements?

http://jsfiddle.net/1vdryy3L/1/

// To start, we will gather all possible keys (e.g. "-JpgJnANTpQFprRieImv")
var keys = [];
for (var i in data) {
    for (var j in data[i]) {
        if (keys.indexOf(j) == -1) {
            keys.push(j);
        }        
    }
}

var result = {}, tmp, k;
for (i in keys) {
    tmp = []; k = 0;
    for (var j in data) {
        if (data[j][keys[i]]) {
            tmp.push([k, data[j][keys[i]].totalVisitors]);
        } else {
            tmp.push([k, 0]);
        }
        k++;
    }
    result['array' + i] = tmp;
}

console.log(JSON.stringify(result));

Answer №2

If you're utilizing jQuery, this code snippet should do the trick for you. In case you're not using jQuery, feel free to swap out the jquery statements with standard JavaScript ones. You can check out a demo on jsfiddle here:

var groupA = []
var groupB = [];
var myData = {
  "1433203200000" : {
    "-JpgJnANTpQFprRieImv" : {
      "events" : 5,
      "name" : "Home office",
      "returningVisitors" : 9,
      "totalVisitors" : 50
    },
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "events" : 10,
      "name" : "Samin Place",
      "returningVisitors" : 32,
      "totalVisitors" : 68
    }
  },
  "1433289600000" : {
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "name" : "Samin Place",
      "newVisitors" : 1,
      "returningVisitors" : 25,
      "totalVisitors" : 26
    }
  },
  "1433376000000" : {
    "-JpgJnANTpQFprRieImv" : {
      "events" : 5,
      "name" : "Home office",
      "returningVisitors" : 9,
      "totalVisitors" : 9
    },
    "-JqsQjFTjHpzKqWgE_KJ" : {
      "events" : 10,
      "name" : "Samin Place",
      "returningVisitors" : 32,
      "totalVisitors" : 32
    }
  }
} 
var counter = 0;
$.each(myData, function(key, value){
    if (value["-JpgJnANTpQFprRieImv"]){
        groupA.push([counter, value["-JpgJnANTpQFprRieImv"]["totalVisitors"]])
    } else {
        groupA.push([counter, 0])
    }
    if (value["-JqsQjFTjHpzKqWgE_KJ"]){
        groupB.push([counter, value["-JqsQjFTjHpzKqWgE_KJ"]["totalVisitors"]])
    } else {
        groupB.push([counter, 0])
    }
    counter++;
});

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

Unable to execute findOneAndUpdate as a function

I've been researching all morning and testing different solutions, but I'm still unable to resolve this issue. Every time I run the code below, I receive the error "TypeError: req.user.findOneAndUpdate is not a function": req.user.findOneAndUpd ...

What is the best way to effectively expand React Bootstrap components?

In order to add sizing functionality to a badge component, I have developed the following approach: import React from 'react'; import Badge from 'react-bootstrap/Badge'; import classNames from 'classnames'; const CustomBadge ...

Retrieve information from a group of strings

I am working with a string collection that looks like this: SetDEL_Stores.Add(DealerCode + "," + ItemIdentityCode.Text + "," + decimal.Parse(Qty.Text) + "," + DateTime.ParseExact(ExpireDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture) + "," + BatchNu ...

What are the reasons behind the min and max range method not providing accurate results?

I am in need of a method that can verify if a given value falls within the valid range of -064.000000 to -180.000000 and 142.000000 to 180.000000. The structure of my ranges object is as follows: "ranges": { "range1": { "min& ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Transmitting C# data to a JavaScript script through JSON serialization. Issue encountered: Character invalid

I'm facing an issue with sending data from my Entity Framework database to a JavaScript script on my webpage. Below is the snippet of code from my MVC Controller: public ActionResult Index() { var wordsToShow = db.Words.Where(w => w.O ...

Error: An unrecognized symbol '<' was encountered while utilizing $routeparams

In my Angular application with MongoDB, Express, and Node.js, I have a list of flats and I want to add an "Edit" option for each flat. Below is a snippet from my api.js file: api.route('/flats/:id') .get(function(req, res){ Flat.findById(r ...

Select a checkbox from a dropdown menu

I need help with automatically checking a checkbox when an option is selected from a dropdown menu. Here is an example of the HTML code: <table> <tr> <td> <input type="checkbox" name="check1" />Process 1:< ...

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

Tips for displaying array data in a row within a React table

I am a beginner in React and I have successfully used the react-table component to display data from Firebase. constructor(props) { super(props); this.state = { vehicles: [] }; } getvehicles() { let vehicles = []; fireb ...

Is it possible to generate files on Firebase post-deployment?

Currently, I am utilizing the node modules: cross-spawn, execa, and spawn-cmd, to execute an application. Interestingly, everything runs smoothly when the application is launched on localhost. However, upon deployment to Firebase and subsequent execution f ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

Continuously monitor the condition in my function

I'm encountering an issue with my jQuery function where it animates a progress bar from 0 to 100 when it's visible on the screen. The problem arises when the progress bar is not initially visible upon page load, as the animation will never trigge ...

What is the best way to assign a class to a read-only field in HTML and CSS?

My situation is as follows: I have jQuery code that uses an if-statement to add a specific class to an element based on the selected value on a form page. I also created another form where users can view the details of a previously filled out form. However ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

Encountering an "Unknown Provider" issue while trying to inject a provider from another module into a

Having trouble with two modules, module A and module B, that are interdependent. Module A is currently in the process of being bootstrapped. I need to inject a provider from module A into the config block of module B. Unfortunately, I keep getting an erro ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Adjust the size of the external JavaScript code

Is it possible to adjust the size of the div element created by the external javascript code below? I've tried wrapping it in a div and setting the width, but the resizing doesn't seem to work. <div width = "100"><script type="text/jav ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...