What is the best way to form a new array using a provided list?

My JavaScript code includes an array and a list.

const headr = [H1, H2 ,H3, H4]
const Year = ['1Y', '2Y' ,'3Y', '4Y']
let arr_ = {
    H1 : Array(3)
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
    1 : {Year: '2Y', Type: 'TypeA', Value: -11928080380}
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
    H4 : Array(4)
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
    1 : {Year: '2Y', Type: 'TypeB', Value: -11928080380}
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
    3 : {Year: '4Y', Type: 'TypeA', Value: 32370503415}
}

I would like to transform this data into a new array structured as shown below:

H1 : Array(3)
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
    1 : {Year: '2Y', Type: 'TypeA', Value: -11928080380}
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
    3 : {Year: '4Y', Type: '-', Value: 0}

    H2 : Array(4)
    0 : {Year: '1Y', Type: '-', Value: 0}
    1 : {Year: '2Y', Type: '-', Value: 0}
    2 : {Year: '3Y', Type: '-', Value: 0}
    3 : {Year: '4Y', Type: '-', Value: 0}

    H3 : Array(4)
    0 : {Year: '1Y', Type: '-', Value: 0}
    1 : {Year: '2Y', Type: '-', Value: 0}
    2 : {Year: '3Y', Type: '-', Value: 0}
    3 : {Year: '4Y', Type: '-', Value: 0}
    
    H4 : Array(4)
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364}
    1 : {Year: '2Y', Type: 'TypeB', Value: -11928080380}
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415}
    3 : {Year: '4Y', Type: 'TypeA', Value: 32370503415}
}

How can I achieve this desired array format? One approach I am considering is creating a new dictionary or array structured like the following example and using a for loop for pushing values:

let dict_ = {
        'H1' : [], 'H2' : [], 'H3' : [], 'H4' : []
    }

Answer №1

To effectively store and retrieve data, it is recommended to utilize a map data structure. In this approach, the headers are used as keys while the corresponding arrays of data serve as the values. By employing the map, you can easily access the data associated with each header.

const headr = ['H1', 'H2' ,'H3', 'H4']
const Year = ['1Y', '2Y' ,'3Y', '4Y']

let arr_ = {
    H1 : Array(3),
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364},
    1 : {Year: '2Y', Type: 'TypeA', Value: -11928080380},
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415},
    H4 : Array(4),
    0 : {Year: '1Y', Type: 'TypeA', Value: -41445643364},
    1 : {Year: '2Y', Type: 'TypeB', Value: -11928080380},
    2 : {Year: '3Y', Type: 'TypeA', Value: 32370503415},
    3 : {Year: '4Y', Type: 'TypeA', Value: 32370503415}
}

let map = new Map();

for (let i = 0; i < headr.length; i++) {
    let header = headr[i];
    let data = arr_[header];
    if (data) {
        map.set(header, data);
    } else {
        let emptyData = [];
        for (let j = 0; j < Year.length; j++) {
            emptyData.push({
                Year: Year[j],
                Type: '-',
                Value: 0
            });
        }
        map.set(header, emptyData);
    }
}

Instead of directly copying the code snippet provided, I aim to illustrate my approach towards resolving this issue.

Answer №2

const headers = ['H1', 'H2' ,'H3', 'H4'];
const years = ['1Y', '2Y' ,'3Y', '4Y'];
const dataObj = {
  H1: [
    {Year: '1Y', Type: 'TypeA', Value: -41445643364},
    {Year: '2Y', Type: 'TypeA', Value: -11928080380},
    {Year: '3Y', Type: 'TypeA', Value: 32370503415},
  ],
  H4: [
    {Year: '1Y', Type: 'TypeA', Value: -41445643364},
    {Year: '2Y', Type: 'TypeB', Value: -11928080380},
    {Year: '3Y', Type: 'TypeA', Value: 32370503415},
    {Year: '4Y', Type: 'TypeA', Value: 32370503415},
  ]
}

const finalResult = headers.reduce((acc, h) => {
  acc[h] = [...dataObj[h] || []];
  years.forEach(y => {
    if (!acc[h].some(({Year}) => Year === y)) {
      acc[h].push({
        Year: y,
        Type: '-',
        Value: 0,
      });
    }   
  });
  return acc;
}, {})

console.log(finalResult);

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

Find the positions of elements in a numpy 1D array that are larger than the element that precedes them

Imagine I have created a 1-dimensional numpy array like so: r=np.random.randint(0,10,(10,)) For instance, it might look like this: array([1, 5, 6, 7, 7, 8, 8, 0, 2, 7]) To find the indices where each element is greater than the one before (to the left) ...

How can I control audio playback with just a click on an image on an HTML webpage?

I attempted to use a code from this website, but it doesn't seem to be working for me. I was hoping that someone here could lend a hand. The code I tried makes the song play when I click the gif image, but when I click it again, it just restarts. H ...

What is the process for changing an array of bytes into a String in Java?

Is there a way to transform an array of bytes into a String without any conversion? I attempted the following: String doc = new String(bytes); However, the contents of the doc file do not match the original byte values (as the bytes represent binary i ...

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

What is the best way to paginate a dynamically updated data table using AJAX in Laravel?

I'm currently facing an issue with rendering a Blade template in Laravel. The template includes an HTML table populated with data fetched via AJAX, and I need to implement manual pagination using Laravel's LengthAwarePaginator. The main Blade fi ...

I am receiving an undefined response from Cheerio when attempting to fetch JSON data

My goal is to create a web scraper and I have successfully downloaded the HTML. Now, with this code snippet, I am attempting to extract the title from my HTML: fs.readFile(__filename.json , function (err, data) { if(err) throw err; const $ = cheerio.load ...

Perl encountering issues with array references

Can someone please provide guidance on how to properly reference the arrays @names and @numbers? I am currently receiving warnings stating that using @names->[$count] is deprecated. I have searched for solutions and found suggestions to use $names->[ ...

Merge Mongo Documents after performing various lookups within a unified aggregation operation

I can't figure out how to merge the results from my document. Below is the query and data I am working with: {"_id":"5c21ab13d03013b384f0de26", "roles":["5c21ab31d497a61195ce224c","5c21ab4ad497a6f348ce224d","5c21ab5cd497a644b6ce224e"], "agency":"5b4a ...

Filter should be applied to all rows except the first one

I am currently working on applying multiple filters to a dynamic HTML table. Everything seems to be running smoothly, except for the fact that the first row contains headings such as empID, Name, etc., which should not be considered as data rows since they ...

I'm having trouble getting my Threejs Raycast to properly intersect with the scene's children. Can anyone offer some guidance

Post 1) I'm currently working on a project where I need to detect all objects visible to the camera so I can reposition them back to their starting point once they go out of view. The goal is to create an infinite waterfall effect by reusing existing ...

React application component fails to render due to conditional logic not being met

The implementation of this component seems correct to me. If the variable isReceivedSession is true, a <ReactFragment/> will be rendered; if it is false, a <Spinner/> should be displayed Inside the fragment, if either isLoadingApp or isLoading ...

What is the best way to update multiple occurrences of a value in an array?

I need to develop a program for an elimination game. The user must provide the number of players and the number of "cycles" that determine how the program progresses. For instance, if I specify 8 players and 4 cycles, the first player eliminated will be ...

Understanding the process of reading long values within a JSON object using JSON.NET

Below is an example of a JSON object: "bookshelf": { "shelfId": 5752814017970176, "shelfName": "Novels", "description": null, "bookOrder": "[5720369633689600, 5631072867975168, 5765651641663488, ...

Switching measurement unit to jQuery when retrieving image weight

After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...

Attempting to make initials fade and slide out upon mouseover using jQuery

I've been experimenting with jQuery to create a unique effect where hovering over my initials in the header expands the containing div and reveals my full name letter by letter. However, I'm facing some challenges and could use some guidance on t ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

Validation of input in React using the onChange event handler

When trying to validate a numeric input using onChange in React, I encountered an issue where the input clears and React throws a ReferenceError: value is not defined. This error makes sense since there is nothing to validate when the input is empty. I ca ...

What is the best way to send props and trigger a function with a single onclick event?

Is there a way to receive a prop and activate a function using the same onclick event? In the navbar.js file, the props are passed like this: <Hamburger menuOpen={this.ToggleMenu} /> In the Hamburger.js file, the props are received. Currently, the ...

What are the steps to implement Vuelidate 2 in a web browser?

Back in the stone age, we used to just drop in a .js file or a CDN reference and start coding. But now things seem much more complicated. I'm trying to use Vuelidate 2 in the browser, but I can't seem to figure it out. I've already done npm ...