What is the best way to merge several nested arrays in JavaScript?

In my data, I have 2 sets of nested arrays:

var values = [[100, 87.5, 87.5, 87.5, 100, 100],
[87.5, 100, 100, 100, 87.5, 87.5],
[75, 75, 75, 75, 75, 75],
[50, 50, 50, 62.5, 62.5, 62.5],
[62.5, 62.5, 62.5, 50, 37.5, 50],
[0, 0, 0, 0, 0, 0]];

var date = [["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"],
["2015", "2004", "2015", "2015", "2015", "2015"]];

My goal is to combine each array in Values and Date like this:

Extract: [100, 87.5, 87.5, 87.5, 100, 100]
Extract: ["2015", "2004", "2015", "2015", "2015", "2015"]

Then merge them into one combined array as shown below:

[{y: 100, d: 2015},{y: 87.5, d: 2004},{y: 87.5, d: 2015},{y: 87.5, d: 2015},{y: 100, d: 2015},{y: 100, d: 2015}]

An example can be found here: https://jsfiddle.net/zidski/5808pgs4/3/

 var result = values.map(function (n, i) {
            return ({ y: n, d: values[i] });
        });

However, the entire array ends up being added together.

Answer №1

Make sure to loop through the inner array as well.

var date = [  ["1998", "2002", "1995", "2010", "2013", "2008"],  ["1999", "2003", "1996", "2011", "2014", "2009"],  ["2000", "2004", "1997", "2012", "2015", "2010"],  ["2001", "2005", "1998", "2013", "2016", "2011"],  ["2002", "2006", "1999", "2014", "2017", "2012"],  ["2003", "2007", "2000", "2015", "2018", "2013"]];

var values = [  [100, 87.5, 87.5, 87.5, 100, 100],  [87.5, 100, 100, 100, 87.5, 87.5],  [75, 75, 75, 75, 75, 75],  [50, 50, 50, 62.5, 62.5, 62.5],  [62.5, 62.5, 62.5, 50, 37.5, 50],  [0, 0, 0, 0, 0, 0]];

var result = values
  // loop through the values array
  .map(function(arr, i1) {
    // loop through the inner array
    // if you only need the first element as in your example, you can remove the first map method and replace `arr` with `values[0]` and `date[i1][i2]`  with `date[0][i2]`
    return arr.map(function(n, i2) {
      // create the necessary array object based on index
      return {
        y: n,
        // retrieve the period from the 2D array date using index
        periods: date[i1][i2]
      }
    });
  });

document.getElementById("data").innerHTML = JSON.stringify(result, null, 3);
<pre id="data"></pre>

Answer №2

One way to organize the values is by using a nested mapping technique.

var data = [[10, 20, 30, 40, 50], [15, 25, 35, 45, 55], [5, 10, 15, 20, 25]],
    labels = [['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O']],
    formattedData = data.map(function (row, i) {
        return row.map(function (value, j) {
            return { label: labels[i][j], number: value };
        });
    });
    
console.log(formattedData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you combine both arrays into a single one, the process becomes straightforward (providing that they have equal lengths):

var years = [["2016", "2008", "2013", "2014", "2015", "2017"],
    ["2016", "2010", "2014", "2016", "2015", "2019"],
    ["2016", "2012", "2015", "2016", "2015", "2020"],
    ["2016", "2014", "2015", "2016", "2015", "2021"],
    ["2016", "2016", "2015", "2016", "2015", "2022"],
    ["2016", "2018", "2015", "2016", "2015", "2023"]];
    
    var amounts = [[120, 85.5, 85.5, 85.5, 120, 120],
    [85.5, 120, 120, 120, 85.5, 85.5],
    [70, 70, 70, 70, 70, 70],
    [45, 45, 45, 57.5, 57.5, 57.5],
    [57.5, 57.5, 57.5, 45, 32.5, 45],
    [10, 10, 10, 10, 10, 10]];
    
    var flattenedAmounts = [].concat.apply([], amounts);
    var flattenedYears = [].concat.apply([], years);
    
     var output = flattenedAmounts.map(function (num, index) {
                return ({ value: num, year: flattenedYears[index] });
            });
            
    
    
    document.getElementById("display").innerHTML = JSON.stringify(output);
<pre id="display"></pre>

Answer №4

Perhaps what you are looking for can be achieved with the following code snippet:

// By using concat, we flatten the arrays.
var result = [].concat.apply([],dates.map(function (subDates, i) {
      // Iterate through the sub dates
      return subDates.map(function(date, j){
         // Create the object
         return { y: date, periods: values[i][j] };

     })
 }));

console.log(result);

// Expected Output:
//[{"y":"2015","periods":100},{"y":"2004","periods":87.5},{"y":"2015","periods":87.5},{"y":"2015","periods":87.5},{"y":"2015","periods":100},...]

Answer №5

To effectively process the data, it may be necessary to perform mapping twice.

var resultData = date.map(function(item,indexDate){
  return item.map(function(year, indexYear){
     return {y:year,d:values[indexDate][indexYear]};
   }); 
});

Another option is to flatten the array. Here is an example on a plunkr for reference.

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

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

Unable to utilize console.log and alert functions within the Next.js application

I'm currently facing a problem in my Next.js application where the console.log and alert functions are not functioning as intended. Despite checking the code, browser settings, and environment thoroughly, pinpointing the root cause of the issue remain ...

Exploring Vue's feature of passing props and emitting events within nested components

Within my coding project, I am facing the challenge of properly implementing a parent component containing a form that includes a birthday component. This birthday component consists of two separate components within it. My task is to effectively pass prop ...

VueJS - Create a dynamic timer using setInterval function

I have a function that is initially triggered within the 'mounted' lifecycle hook, and then it continues to be called every 15 minutes. In my component, I am looking to showcase a countdown until the next setInterval in minutes and seconds. asyn ...

What is the best way to incorporate a jQuery progress bar into a slideshow gallery?

My friend and I are working on enhancing our jQuery slideshow by adding a progress bar to show when the gallery will switch to the next image. Here is the code for our slideshow that we have written so far. We would greatly appreciate any help or suggestio ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...

Filter Vue JS search results using an array of checkboxes

Recently, I created a custom Vue JS search feature for filtering properties on a real estate website. This search component is displayed on every page, so I decided to utilize a URL search query approach. By extracting the search parameters using this.$rou ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...

What is the best way to notify an XML file using jQuery?

I am encountering an issue with a login api when trying to send an xml document. The error occurs when including '<?', but I need to send the whole XML with it. Can someone assist me in sending the complete XML using a different method or type ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Display JSON information within a Bootstrap modal

Hi there! I'm just starting to learn about ajax, json, and modals. I have some data displayed in the console that I want to show in a modal pop-up. Specifically, when I click on the view request button for each employee, I should see their individual ...

An error occurred while trying to convert a circular data structure to JSON during an API request within another

Attempting to make an API call within another API call in this code, however encountering the following error: Error: Converting circular structure to JSON const express = require('express'); const router = express.Router(); const config = requi ...

Accessing the window variable within a Jquery selector in Javascript

I'm encountering some issues while attempting to optimize code. The following lines execute without errors: Array.prototype.forEach.call( $('ZA1 .stat'), function( td ) {//ExcuteCode} Array.prototype.forEach.call( $('ZA2 .stat'), ...

The error function is consistently triggered when making an Ajax POST request, even though using cURL to access the same

I have been using Ajax's POST method to retrieve a JSON response from the server. However, whenever I click the button on my HTML page, the Ajax function always triggers the error function, displaying an alert with the message "error." Below is the co ...

Transferring information using pure JavaScript AJAX and retrieving it through a Node API

On the client side, I have the following code: sendMail(e) { e.preventDefault(); var name = document.getElementById('name').value; var contactReason = document.getElementById('contactReason').value; var email = document ...

Activation of navigation buttons in the Vue Full Calendar control the movement to the next and previous

In my current project, I am utilizing https://www.npmjs.com/package/vue-full-calendar. However, I have encountered an issue when trying to receive callbacks or triggers from the next and previous buttons on the calendar. My backend API is structured aroun ...

Older browser compatibility for Flexbox flex-flow alternative

<template> <div> <h2>Kanal Listesi</h2> <div class="container"> <div v-for="(channel,index) in channels" :key="index"> <div v-if="channel.ChName"> <img :src="'h ...

Locate a specific text within a complex array of objects and retrieve the objects that contain the match as

I have an array of objects named input as shown below. Each object in the array contains a property vertical of type string, an array called platformList, and a nested object named radar_metadata. I am looking to implement a search functionality where I c ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

What is the process for changing the background color with Angular?

It should be a straightforward task, but for some reason, it just won't cooperate. Within my controller: $scope.projects = [ //... { background: "#ffffcc" }, //... ]; In the HTML: <div ng-repeat="project in projects" ng-style="{ ...