What could be causing the excessive number of entries in my mapping results?

I am in need of mapping an array consisting of dates. Each date within this array is associated with a group of dates (formatted as an array).

For instance: The format array looks like this:

let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10];

This indicates that the first three dates in the dates array belong to one group, the next 3 dates belong to another group, and so on.

Therefore, I expect my output to consist of 16 items (matching the length of the format array). The desired output would look something like this: For the first group of dates: Start: lowest date in that group End: highest date in that group

However, the current output is simply returning entries based on the number of dates.

let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10];
let dates = [
  // Insert sample dates here
];

var numTimesUsed = 0;
var nameIndex = 0;
let app_multiple = dates.map(function combineTitleData(dataItem, index) {
  if (format[nameIndex] == numTimesUsed) {
    nameIndex++;
    numTimesUsed = 0;
  }
  numTimesUsed++;
  let end = new Date(dates[nameIndex]);
  end.setDate(end.getDate() + parseInt(format[nameIndex]) - 1);
  return {
    start: dates[nameIndex],
    end: end
  };
});
//
console.log(app_multiple);

Thank you

Answer №1

Using the Splice method will help retrieve specific groups from an array.

const res = format.map(num => dates.splice(0,num))

let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10];
let dates = [ "2021-10-04T04:00:00.000Z", "2021-10-05T04:00:00.000Z", "2021-10-06T04:00:00.000Z", ... (omitted for brevity)]

const res = format.map(num => {
  const arr = dates.splice(0,num)
  const start = arr.shift();
  const end = arr.length === 0 ? start : arr.pop();
  return { start, end }
})
console.log(res)

To obtain an array of objects containing start and end values (only start if no end), you can implement this solution - assuming the date strings are sorted. If unsorted, simply use dates.sort() to sort them.

const res = format.map(num => {
  const arr = dates.splice(0, num)
  const start = arr.shift();
  const end = arr.length === 0 ? "" : arr.pop(); 
  return end ? { start, end } : { start }
})
console.log(res)

let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10];
let dates = [ "2021-10-04T04:00:00.000Z", "2021-10-05T04:00:00.000Z", "2021-10-06T04:00:00.000Z", ... (omitted for brevity)]

const res = format.map(num => {
  const arr = dates.splice(0, num)
  const start = arr.shift();
  const end = arr.length === 0 ? "" : arr.pop()
  return end ? { start, end } : { start }
})
console.log(res)

Alternatively, set start and end to the same value if only one date is present:

const res = format.map(num => {
  const arr = dates.splice(0, num)
  const start = arr.shift();
  const end = arr.length === 0 ? start : arr.pop(); 
  return { start, end }
})
console.log(res)

Answer №2

Map always guarantees the same number of inputs as outputs, so when dealing with dates, don't expect the output array to match the length of the input. To address this issue, we utilize the format as an input parameter for the map function to obtain an array collection.

let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10];
let dates = [
  "2021-10-04T04:00:00.000Z",
  ...
  "2022-01-18T04:00:00.000Z"
];

// Convert strings into dates for comparison
const realDates = dates.map(d => new Date(d));

// Apply map on the format array since it always returns the same number of elements as the input array, hence guiding us to use format instead of dates
const dateGroup = format.map(num => realDates.slice(0,num));

// Iterate over the array to generate a new form
let app_multiple = dateGroup.map(function createNewObject(singleDateCollection, index) {

  return {
    start: new Date(Math.min.apply(null,singleDateCollection)),
    end: new Date(Math.max.apply(null,singleDateCollection))
  };
});
//
console.log(app_multiple);

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 there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

What is the process of incorporating external links into an angular application?

Attempting to embed an external URL within my Angular app using an iframe has resulted in the following issue: https://i.sstatic.net/liSmX.png The error message reads as follows: https://i.sstatic.net/u9GWw.png Below is the template where I am trying t ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

Having trouble using the elementIsNotVisible method in Selenium WebDriver with JavaScript

I'm struggling to detect the absence of an element using the elementIsNotVisible condition in the Selenium JavaScript Webdriver. This condition requires a webdriver.WebElement object, which is problematic because the element may have already disappear ...

Submitting a form using Ajax that was generated with the help of jQuery

Using a table with various rows, each row has an edit button. Upon clicking the edit button, a form is generated using ajax/json to populate the form data based on the selected row. An issue arises when setting up the ajax for this form. Although the met ...

unable to locate the allong.es variadic function

Encountering an Error node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: undefined is not a function at /home/ubuntu/nodejs/test.js:4:10 at factorial (/home/ubuntu/nodejs/test.js:17: ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

The rating system does not accurately incorporate the values provided by the API

Incorporated the star rating package into my ReactJS code to showcase the star value retrieved from a mock API. import { Rating } from "react-simple-star-rating"; However, when attempting to make it read-only, it does become static but fails to ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

What is the best method for storing a 2D array in a Script Property using the Properties Service in Google Apps Script?

Can anyone provide guidance on how to save a 2D array as a property in Google App Script? var array = [['value 1', 1.0, 'A'],['value 2', 2.0, 'B'],['value 3', 3.0, 'C']] PropertiesService.getSc ...

Utilizing JavaScript and Ajax to Dynamically Assign Variables Based on JSON Responses

What could be causing the undefined value of x at line 11, even though it was defined in line 9? <script> var x; $.ajax({ dataType: "json", url: myurl, success: function(data){ console.log(data); x = data; documen ...

Implementing Angular CDK for a dynamic drag-and-drop list featuring both parent and child elements

I'm currently working on setting up a drag and drop list within Angular using the Angular CDK library. My goal is to create a list that includes both parent and child elements, with the ability to drag and drop both parent items as well as their respe ...

Using Highcharts within a Vue.js component

I'm having trouble creating graphical components with Highcharts and Vue.js because I can't figure out how to dynamically set the id attribute that Highcharts needs to render properly. Does anyone know how to set the id dynamically? This is the ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Execute a Jquery function on every field

I need to capitalize each value of the select options that come from a SQL database. However, the code provided only works on the first field... function capitalize(str){ var text = str.text().replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCas ...

Error: When attempting to send a message in a different channel, an undefined property 'send' is encountered causing a TypeError

I'm utterly stumped as to why I keep encountering this issue, so perhaps someone here can shed some light on it. The error message reads: TypeError: Cannot read property 'send' of undefined Here is the snippet of code in question: client.o ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

Issue with Jquery .scroll() not functioning in Internet Explorer when using both $(window) and $(document). Possible problem with window.pageYOffset?

Here is the code snippet I am currently struggling with: $(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 200; if(y_scroll_pos > scroll_pos_test) { $('.extratext').slideDown(&a ...