Obtain the initial data value and store it in an array for each distinct date

Below is a data object that needs to be iterated through using JavaScript in order to extract one "value" field into an array for each unique date.

While I am able to retrieve all the data, my goal is to collect one value for each distinct date (ignoring the time component).

{
  name: "test", 
  data: Array(200)
}

data: Array(200) 
0: {
  @id: "p23o"
  code: "02"
  dateTime: "2018-12-12T04:38:00Z"
  value: -0.645
}  
1: {
  @id: "p453o"
  code: "02"
  dateTime: "2018-12-12T07:48:00Z"
  value: -0.3645
} 
2: {
  @id: "p4423o"
  code: "032"
  dateTime: "2018-12-11T07:13:00Z"
  value: -0.645
} 
+ 198 more objects

The resulting array should contain one value per day. What is the correct way to iterate over this data and create the desired array? Are there any best practices or recommended methods for accomplishing this task?

Thank you for your help!

Answer №1

Transform your date string into a Date object using the Date constructor, then strip the time from the date.

Follow the code below:

// Your response data will be stored in the variable 'data'
var uniqueData = {};
data.forEach(item => {
   var date = new Date(item.dateTime);  
   var onlyDaysTime = new Date(date.getYear(), date.getMonth(), 
       date.getDate());
   var key = onlyDaysTime.toString();

   if(typeof uniqueData[key] === 'undefined') {
      uniqueData[key] = [];
   }
   uniqueData[key].push(item);
})

for(key in uniqueData) {
  console.log(uniqueData[key]);
}

Output:

[[object Object] {
  code: "02",
  dateTime: "2018-12-12T04:38:00Z",
  id: "p23o",
  value: -0.645
}, [object Object] {
  code: "02",
  dateTime: "2018-12-12T07:48:00Z",
  id: "p453o",
  value: -0.3645
}]
[[object Object] {
  code: "032",
  dateTime: "2018-12-11T07:13:00Z",
  id: "p4423o",
  value: -0.645
}]

Try it out on JSBin: https://jsbin.com/juwekiduju/edit?js,console

Answer №2

To effectively store the object corresponding to each unique date in an object accumulator, you can utilize array#reduce. Subsequently, all values from this object can be retrieved using Object.values()

let data = [{ "@id": "p23o", code: "02", dateTime: "2018-12-12T04:38:00Z", value: -0.645 } , { "@id": "p453o", code: "02", dateTime: "2018-12-12T07:48:00Z", value: -0.3645 } , { "@id": "p4423o", code: "032", dateTime: "2018-12-11T07:13:00Z", value: -0.645 }],
    result = Object.values(data.reduce((r,o) => {
      let date = o.dateTime.substring(0,10);
      if(!(date in r)) r[date] = {...o};
      return r;
    },{}));
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

What is the best way to produce a random integer within the range of 0 and 2

Here is the code snippet: var i = prompt('Please choose Rock, Paper or Scissors:'); var b = ['Rock', 'Paper', 'Scissors']; Now, I need help in generating a random number between 0-2. My initial idea was to do t ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Converting the jQuery $.xajax loadmore feature into a custom XMLHttpRequest JavaScript function

I'm facing challenges while trying to create a XMLHttpRequest loadmore function as compared to using $.ajax. I am uncertain about what I might be missing in my code. Below is the function that is based on a previously working $.ajax version that I ha ...

Enveloping an immediate search within a JavaScript throttle function

Below is a code snippet for a cloud tag (Goat1000) with an instant query. The query part should be enclosed within the throttle function from the underscore.js library to prevent server crashes. <script src="underscore-min.js"></script> &l ...

What is the process for deactivating a range of dates?

I am trying to prevent users from selecting dates within the range specified by l1 and l2. However, my current method only disables the date 13. var l1 = new Date("2019-07-13"); var l2 = new Date("2019-07-30"); this.flag = 0; this.filter2 = function( ...

Is there a way to utilize a parameter for the user's input instead of relying on document.getElementById when incorporating a button?

let totalScore = 0; var myArray = [1, 2, 3, 4, 5]; let randomNum; function NumGuess(userInput) { var userGuess = userInput; var i; for (i = 0; i < 1; i++) { var randomNum = myArray[Math.floor(Math.random() * myArray.length)]; } if (us ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

Incorporate various pieces of information into an object

Hey everyone, I need some help with my ServiceNow code. I have a JavaScript doubt regarding it. I am attempting to display data in a marquee. <div> <marquee><b ng-repeat='val in data.arr'><label>{{val.display_field}}</ ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

The event listener for a button click is triggered just a single time

There seems to be an issue with the click listener not firing after the first time in my class where I have multiple buttons for selecting a number. I've created a simplified version on CodePen (https://codepen.io/jasonws/pen/qBZeMMB) to showcase the ...

Creating several divs with an image tag within each div individually using Jade HTML pre-processor

Check out the code snippet below: <div id="cubeSpinner"> <div class="face one"> <img src="/images/Windows%20Logo.jpg" class=""> </div> <div class="face two"> <img src="/images/Turtle.jpg" class ...

Guide on extracting data from a JavaScript table using Python

Looking to extract information from a table on this page: . There are a total of 18 pages, but the url remains constant for each page. My usual method involves using BeautifulSoup to scrape data from HTML pages. However, in this case, the required data is ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

How to create a gelatin-like effect on a rectangle using HTML5 canvas

Currently, I'm working on a platformer game project in JavaScript. The concept involves players as rectangles jumping on and off platforms. While the basic functionality is set up, I'm now aiming to incorporate a unique 'gelatine effect&apos ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Are there any online tools available for generating SSJSON specifically designed for SpreadJS?

Currently utilizing Ubuntu, Ubuntu-Wine, and MS Office 7 on Wine. Interested in converting an xls template to ssjson for testing SpreadJS. Found some sjson file links on the Wijmo forum. Managed to successfully load it into SpreadJS, but unsure if the c ...

What is the best way to extract individual objects from several arrays and consolidate them into a single array?

Currently, I have a collection of objects stored in a variable called listOfObjects. They are not separated by commas because I utilized the Object.entries method to extract these values from another array. console.log(listOfObjects) outputs { q: 'L ...

The preflight response does not permit the authentication request header field to be included in the Access-Control-Allow-Headers

--The issue was caused by a hosting error, but now it's resolved-- I have been working with an express API and I made sure to enable all CORS functionality using the npm cors package. Here is how I implemented it: app.use(cors()) Everything was ru ...

Two pretensions and an evaluation in an if statement

Currently, I am delving into the well-optimized code for voronoi implementation created by Mike Bostock (d3js). I find myself puzzled by the following snippet of code: if (!(m = (halfedges = cell.halfedges).length)) return; You can view the full code he ...