Guide on transforming an array of objects into a fresh array

I currently have this array:

const initialData = [
  {
    day: 1,
    values: [
      {
        name: 'Roger',
        score: 90,
      },
      {
        name: 'Kevin',
        score: 88,
      },
      {
        name: 'Steve',
        score: 80,
      },
    ],
  },
  {
    day: 2,
    values: [
      {
        name: 'Roger',
        score: 70,
      },
      {
        name: 'Michael',
        score: 88,
      },
    ],
  },
  {
    day: 3,
    values: [
      {
        name: 'Steve',
        score: 97,
      },
    ],
  },
];

which needs to be transformed into the following format:

const result = [
  {
    name: 'Roger',
    scores: [90, 70, null],
  },
  {
    name: 'Kevin',
    scores: [88, null, null],
  },
  {
    name: 'Steve',
    scores: [80, null, 97],
  },
  {
    name: 'Michael',
    scores: [null, 88, null],
  },
];

I've been attempting to accomplish this by utilizing map on the array and creating a temporary holder array:

const holder = [];

initialData.map()

However, I haven't been successful in my attempts.

Answer №1

To achieve this, it is advisable to follow a two-step process - commence with the reduce method to enable indexing by name, and then proceed with the map function to transform the entries as per your desired format.

const initialData = [{day:1,values:[{name:"Alice",grade:90},{name:"Bob",grade:88},{name:"Charlie",grade:80}]},{day:2,values:[{name:"Alice",grade:70},{name:"Eve",grade:88}]},{day:3,values:[{name:"Charlie",grade:97}]}];


var result = Object.entries(initialData.reduce( (acc,item) => {
  item.values.forEach( v => {
    if(!acc[v.name]) acc[v.name] = {};
    acc[v.name][item.day] = v.grade;
  });
  return acc;
},{})).map( ([name,days]) => ({  
    name,
    grades: new Array(initialData.length).fill(null).map( (_,i) => days[i+1] || null)
}))

console.log(result);

Answer №2

To generate an array from the given data using reduce and forEach, you can create individual objects for each name. Then, to retrieve an array from these objects, simply utilize the Object.values method.

const info = [{"day":1,"values":[{"name":"Roger","score":90},{"name":"Kevin","score":88},{"name":"Steve","score":80}]},{"day":2,"values":[{"name":"Roger","score":70},{"name":"Michael","score":88}]},{"day":3,"values":[{"name":"Steve","score":97}]}]

const object = info.reduce((resultObj, { values }, index) => {
  values.forEach(({ name, score }) => {
    if (!resultObj[name]) resultObj[name] = { name, scores: Array(info.length).fill(null)}
    resultObj[name].scores[index] = score
  })
  
  return resultObj;
}, {})

const finalArray = Object.values(object)

console.log(finalArray)

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

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

Jenkins process encounters issues with sed execution

I am currently facing an issue where a script that runs successfully locally encounters difficulties during our Jenkins build process, specifically with the 'sed' command. Below is the code snippet I am using. I have double-checked the file path ...

Concealing Dropdown Box Information Based on a Customized List in Angular

Is there a way to remove an item from a dropdown list once it has been selected? For example, if I have a dropdown box with options 'Dog', 'Lion', and 'Cat', how can I make it so that once I select 'Dog', it will no ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

ReactJS bug: Array rendering problem affected by recent changes

Why does ReactJS remove the first element instead of the middle element when using array.splice to remove an element from an array? This is my code. I am using Redux as well. const reducerNotesAndLogin = (state = initialState, action) => { var tableNo ...

Using node modules within an HTML document

I'm finding it challenging to understand how npm handles dependencies when it comes to referencing them in HTML. For example, if I have a specific version of a plugin installed that includes the version number in its path or file name, and npm is set ...

Value becomes null when updating in Node.js

I've been working on updating a value through API calls in express and node js. Here is how my route is set up: var express = require('express'); var router = express.Router(); router.put('/updateValue/:id', function(req, res, ne ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

Ways to determine the current page I am viewing

I am working with a list of tabs and I need to track my current location every time I click on a specific tab. My MainCTRL controller, which is the parent of all tab controllers, needs to be aware of the active tab at any given moment. I attempted to use n ...

An issue has arisen regarding the type definition for the random-string module

I am currently working on creating a .d.ts file for random-string. Here is the code I have so far: declare module "random-string" { export function randomString(opts?: Object): string; } When I try to import the module using: import randomString = ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

Material UI is failing to apply its styles

I tried customizing the default theme provided by Material UI, but unfortunately, the styles are not applying. Can anyone help me with this issue? In My Header.js file, I faced an issue where the customized style was not being applied as expected. const u ...

Is dirPagination failing to display pagination links correctly?

I am currently attempting to implement server-side pagination in my application, but I am facing challenges as the paging option seems to be missing. I have been following this tutorial for guidance. Below is a snippet of my code: JavaScript: $scope.vm= ...

Unleashing the Power of Node Js: Retrieving File Data and Form Data in POST Requests

When sending form data values using Postman, you can utilize a NodeJS server in the backend to handle the POST request. Here is an example of how to structure your code: require('dotenv').config(); const express = require('express'); co ...

What is the best way to receive a notification when a user chooses any option in a Material UI Autocomplete React component?

My dilemma involves using an autocomplete feature that doesn't behave as expected. I am looking to detect when an option is selected, regardless of whether it's the same as the last selection. The onChange event I'm using only triggers if th ...

Error: Cannot access collection property of dbObject

I've been working on fetching data from a database, but I've hit a roadblock. I keep encountering an error and can't seem to figure out what's causing it. I've searched for solutions but haven't found one that works yet. I&apo ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

"Performance issues with Three.js due to too many textures in 200

I have been experimenting with three.js for a few months now. Recently, I began working on a project involving a 3D webgl product catalogue where we store base64 images in the browser's indexeddb and create the catalogue upon app load. The issue arise ...

Remove all $.ajax requests from content that has been loaded using $.ajax in jQuery

I'm currently working on a page where users can click a link to load content using $.ajax into a designated container div. However, I've encountered an issue with multiple clicks causing an increase in the number of $.ajax requests and resulting ...