Iterating through an array of objects to generate a new array for each item that shares a common value at a specific index

I'm trying to figure out how to create an array that stores all the visits values for each unique date without duplicating the date arrays.

const MOCK = {
        data: [
          {date: "Aug.03", name: "Nihal Pandit", visits: 3 },
          {date: "Aug.03", name: "Anthony Elias", visits: 3 },
          {date: "Aug.04", name: "Alex P.", visits: 2 },
          {date: "Aug.05", name: "Alex P.", visits: 3 },
          {date: "Aug.05", name: "Anthony Elias", visits: 3 },
        ]
     }

While looping over an array, I need a method to compare values between iterations. I think Array.reduce() might be helpful, but I'm not entirely sure how to implement it correctly just yet.

The desired output should resemble:

[["Aug.03", 3, 3], ["Aug.04", 2], ["Aug.05", 2, 3]]

Essentially, I want an array for each unique date containing all the visit values from objects with that specific date.

let newArray = [];
let visitCountValues = MOCK?.data?.map((item, idx)=> {
        let value = Object.values(item);
      if(value[0] === value[0]){
        newArray.push([value[0], value[1])
      }
        
      }) 

Answer №1

To easily group the elements of an array into a single object with dates as properties, you can utilize the `reduce` method along with `Object.values` to retrieve the mapped arrays.

const MOCK = {
        data: [
          {date: "Aug.03", name: "Nihal Pandit", visits: 3 },
          {date: "Aug.03", name: "Anthony Elias", visits: 3 },
          {date: "Aug.04", name: "Alex P.", visits: 2 },
          {date: "Aug.05", name: "Alex P.", visits: 3 },
          {date: "Aug.05", name: "Anthony Elias", visits: 3 },
        ]
     }
     
const dateGroups = Object.values(MOCK.data.reduce((acc, { date, visits }) => ({
  ...acc,
  [date]: [...(acc[date] || [date]), visits]
}), {}))

console.log(dateGroups)

Answer №2

Upon reviewing your updated question, I now have a better understanding of what you are looking to achieve. Here is an example of how you can accomplish this:

const userVisits = [
      {date: "Aug.03", name: "Nihal Pandit", visits: 3 },
      {date: "Aug.03", name: "Anthony Elias", visits: 3 },
      {date: "Aug.04", name: "Alex P.", visits: 2 },
      {date: "Aug.05", name: "Alex P.", visits: 3 },
      {date: "Aug.05", name: "Anthony Elias", visits: 3 },
    ]
    
const result = Object.values(userVisits.reduce((res, {date, visits}) =>{
   const existing = res[date] || [date]
   res[date] = [...existing, visits]
   return res
}, {}))

console.log(result)

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

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Angular component with optional one-way binding for version 1.5 and above

Copied from the official AngularJS 1 documentation: To make a binding optional, simply add ?: <? or <?attr. What are the differences between the optional and non-optional one-way bindings? I can't seem to find the dissimilarities for the op ...

Retrieve the Element from the Shadow DOM or leverage the main site's styles

I am currently involved in a project that utilizes Polymer (still on version 1.7, but we are planning to switch to a different technology instead of upgrading). My task involves exploring ways to integrate DynamicYield, a personalization platform that inse ...

Focusing on a text field after reloading a different div with AJAX

I've been spending a lot of time figuring out the following issue and I'm hoping someone can help me find the solution. My web application has an input field (type="text") that is ready to accept user input when the page loads. When the user nav ...

Maintaining duplicate values in a JSON stringify operation: Tips for retention

Server responses are being received in JSON format, which may contain objects with duplicate keys. When displaying the results, I noticed that only the last value for duplicate keys was showing up. After investigating, I realized this was due to using the ...

Having difficulties accessing information from the HTML document

I face an issue with my code where I am unable to fetch the sectionID from tr. I want to retrieve the dynamic id of sectionID on each button click for deletion, but it always returns null. Below is the JQuery script: <script> $(function () { $(&apo ...

Troubleshooting Issues with Ajax using Jquery and ASP.NET

I've been researching this issue on various forums, but I'm having trouble getting it to work. My goal is to implement the ajax function in my asp.net web application Here's the Javascript code from VerifMain.aspx $(document).ready(functi ...

Dabeng Organizational Structure: Implementing PHP, MySQL, and AJAX

Hey there! I need help converting my data from a parent-child loop to dabeng format. You can find more information about the format here. Here's what my current data looks like: $data_cst = array(); foreach($list as $row){ $data = arr ...

Steps to insert an image object into a table

Note: The image in the database is named "profileImage." I want to create a dynamic image object similar to other objects when I insert this code. { label: "Image", name: "profileImage", } It will display the image endpoint as 3704545668418.PNG and ...

Can Authorization be Combined with Filtering in a Node.js RESTful API?

In my current setup, I have a web application communicating with a RESTful API to interact with the database. The frontend of the web app uses Angular HTTP to post/get/put data to the backend, which then manages authentication, interacts with the API, and ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

Executing JavaScript functions from an ASP.NET Razor view is achieved by using the

While working on a view in which I am writing Razor code, I encountered the need to call a JavaScript function with the JSON generated by the Razor code: // JavaScript function function buildTemplate(currentTemplate) { alert('hello world'); } ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Creating Stunning Light Effects in Three.js using Volumetric Shading and Additive Blending

Greetings to all who are taking the time to read this message; I've embarked on a journey to create a model of the Solar System using three.js. My goal is to simulate the Sun with a volumetric light effect similar to the one demonstrated here. Howeve ...

Finding distinct values in a multidimensional array using JavaScript

When working with JavaScript, I created a multidimensional array using the following code: result.each(function(i, element){ init.push({ label : $(this).data('label'), value : $(this).val(), }); }); The resulting array in ...

What could be the reason for the onclick event not being rendered in Bootstrap-Vue

I am facing an issue with a bootstrap-vue b-button that has a v-on:click tag. The problem is that the onclick event is not appearing in the rendered HTML. Here are the dependencies being used: "webpack": "^5.35.1", "webpack-cli&quo ...

Creating divs dynamically in a loop and displaying them upon clicking a button in Angular

I am trying to dynamically create divs in a loop and show the selected div when I press a specific button. In theory, this is how I envision it... <div>div1</div><button (click)="showDiv(divID)">showDIV</button> To hide a ...

Implementing interactive elements such as buttons and controls on an HTML5 canvas

I've been working with the three.js 3D engine and I'm wondering how to incorporate UI buttons onto my WebGL canvas. Any ideas on how to achieve this? ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...