Assign the values of one array to be the keys in a new array

Here is an example of an array:

[
  {date:'27-06-2021',name:'John Doe',count:2},
  {date:'29-06-2021',name:'John Doe',count:1},
  {date:'29-06-2021',name:'George Newman',count:1},
]

I am looking to reformat this array into a new structure where the names become keys and the counts add up based on the dates.

The desired outcome should look like this:

[
  {date:'27-06-2021',John Doe:2,sumCount:2},
  {date:'29-06-2021',John Doe:1,George Newman:1,sumCount:2},
]

Is there a way to achieve this transformation? Any suggestions would be appreciated. Thank you!

Answer №1

One way to improve the array organization is by implementing some basic logic.

const input = [
  { date: '27-06-2021', name: 'John Doe', count: 2 },
  { date: '29-06-2021', name: 'John Doe', count: 1 },
  { date: '29-06-2021', name: 'George Newman', count: 1 },
]

const output = [];
input.forEach((record) => {
  searchNode = output.find((node) => node.date === record.date);
  if(searchNode) {
    searchNode.sumCount += 1;
    if (searchNode[record.name]) {
      searchNode[record.name] += 1
    } else {
      searchNode[record.name] = 1
    }
  }
  else {
    pushNode = {
      date: record.date,
      sumCount: record.count,
    };
    pushNode[record.name] = 1;
    output.push(pushNode);
  }
})
console.log(output);

Answer №2

To achieve this task, you can utilize the Array.prototype.reduce method to gather the dates into a dictionary where the dates serve as unique keys. Then, you can employ Object.values() to extract the values from the dictionary.

const transformedData = Object.values(data.reduce((acc, cur) => {
    // For clarity purposes, I have moved these variables here
    const { date, name, count } = cur;

    // Build the dictionary using `date` as the key
    if (date in acc) {
        acc[date].sumCount += count;
    } else {
        acc[date] = {
            date,
            sumCount: count
        };
    }

    // Names are used as keys to keep track of individual counts
    // If name is nullish, it starts at 0
    acc[date][name] = (acc[date][name] ?? 0) + count;

    return acc;
}, {}));

Here's a proof-of-concept example:

const data = [{
    date: '27-06-2021',
    name: 'John Doe',
    count: 2
  },
  {
    date: '29-06-2021',
    name: 'John Doe',
    count: 1
  },
  {
    date: '29-06-2021',
    name: 'George Newman',
    count: 1
  },
];

const transformedData = Object.values(data.reduce((acc, { date, name, count }) => {
  if (date in acc) {
    acc[date].sumCount += count;
  } else {
    acc[date] = {
      date,
      sumCount: count
    };
  }
  
  acc[date][name] = (acc[date][name] ?? 0) + count;
  
  return acc;
}, {}));

console.log(transformedData);

Answer №3

let information = [
  {date:'27-06-2021',name:'John Doe',amount:2},
  {date:'29-06-2021',name:'John Doe',amount:1},
  {date:'29-06-2021',name:'George Newman',amount:1},
];

information = information.map(function(person)
{
  person[person['name']] = person['amount'];
  delete person['name'];
  delete person['amount'];
  
  return person;
});

console.log(information);

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

Is it possible to encounter an invalid index error when removing a key from an array?

I have an array called $data_list that includes the element date_time with data formatted like this: [0]=> array(2) { ["date_time"]=> string(19) "2014-11-14 09:30:03" ["follower_count"]=> string(4) & ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

how to use jQuery to sort appended data

I have a loop that retrieves data from the server in descending order, but when I use "append()" to add the data, it doesn't maintain the correct sorting. For instance, the first row shows up in the second position. Is there a way to append the data ...

Utilize a function to send an AJAX email

In my JavaScript function, I have been attempting to send an email from a contact form. The validation checks are working correctly, but when the code reaches the point of sending the form, it gets stuck and doesn't receive any response from $.ajax. I ...

Arrangement of elements in MongoDB

In my application, there is a list of games, each with a specific position that determines the order in which they are displayed to users (e.g. 1, 2, 3...). Currently, I am using MongoDB to store all the game data. Let's say I have a game with positi ...

Split a string into numbers and store them in an array in Matlab

My current code takes a string from a text field that contains numbers separated by commas, such as (1,1,1,3,4,7,9,9,9). I then split the string based on commas and store each number in an array using Matlab. However, I am encountering an error when using ...

Incorporating image links within React components

I am currently in the process of learning React. Within my components folder, located inside the src folder of my project, there is a file called website_index.js. Additionally, there is an images folder within the src directory. I am attempting to link im ...

Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc). Here's the div I'm working with: <div id="matchday"> <img id="home ...

Semantic UI dropdown field not displaying selected option text

I've encountered an issue while working with React Semantic UI. I'm trying to render a dropdown and have configured it so that the selected option's text should display in the field. However, when I choose an option from the dropdown, instea ...

Incorporating the fadeout technique in conjunction with the append() function

Here is some code that I am working with: $('body').on('click' , function(){ $('body').append('<div class="ajax-success"><p>Its Done !!!</p></div>').fadeOut(2000); }); The goal was to a ...

What is the JavaScript event object all about?

Can you provide an example of what is considered an 'event object' in the context of this program? Is it, for instance, the <p> element if a <p> is clicked, or the <html> element if <html> is clicked? Or is the event objec ...

Shopping Dialog with Bootstrap (nakupanda) captures form input [JSFiddle]

Having difficulty extracting data from my form. Currently utilizing the bootstrap dialog from nakupanda () The dialog (located within a fullcalendar select function) var form = $('#createEventForm').html(); BootstrapDialog.show({ mes ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

Stopping the continuous re-sending of a script via Ajax when a key is pressed

My script is set up to save messages into a database when the enter key is pressed. <textarea class="comment" name="comment" id="comment" onKeyPress="return checkSubmit(event)" onKeyDown="return checkTypingStatus(event)" >Comment/Reply</textarea& ...

Retrieve the element by clicking on its individual tooltip

I am currently struggling with a jQuery UI tooltip issue. Specifically, I would like to retrieve the element that the tooltip is associated with when clicking on it. My Approach So Far $(".sample").tooltip({ content: function () { return $(t ...

Objects within an array are not sorted based on their properties

I'm currently struggling with sorting an array of objects based on a specific property. Despite my efforts, I can't seem to figure out what's causing the issue as it remains unsorted. Would appreciate some assistance. You can take a look at ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

Is there a pythonic technique for comparing values within an array?

Issue at hand: The challenge: The task at hand involves processing a tab delimited file where rows represent variables and columns represent samples. Each variable can have three values (00, 01, 11) and they need to be in a specific order (v1->vN). D ...

Show Data on the Right-hand Side

Objective: Arrange the component names in two columns - left and right, with different objects like input textboxes based on a browser width of 981px. The desired layout is showcased in this link "https://jsfiddle.net/2w9kskr2/". Challenge: After impl ...