group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into an object resembling a range, indicating the start and end days for each length.

If there is a missing day in the sequence, it should result in an additional range object. For example, if day 33 is removed from the sample data, it would create an extra range object (one from day 31 to 32, another from 34 to 35).

    const data = [
      { day: 31, length: 10 },
      { day: 32, length: 10 },
      { day: 33, length: 10 },
      { day: 34, length: 10 },
      { day: 35, length: 10 },
      
      { day: 68, length: 15 },
      { day: 69, length: 15 },
      { day: 70, length: 15 },
      { day: 71, length: 15 },
      
      { day: 80, length: 10 },
      { day: 81, length: 10 },
      
      { day: 98, length: 12 },
      { day: 99, length: 12 },
      { day: 100, length: 30 },
    ];


    const convertToWindows = (data) => {
      return ...;
    };

    const windows = [
      {
        start: 31,
        end: 35,
        length: 10,
      },
      {
        start: 68,
        end: 71,
        length: 15,
      },
      {
        start: 80,
        end: 81,
        length: 10,
      },
      {
        start: 98,
        end: 99,
        length: 12,
      },
      {
        start: 100,
        end: 100,
        length: 30,
      },
    ];

Answer №1

Consider trying out the following approach:

const info = [
      { num: 15, value: "hello" },
      { num: 16, value: "world" },
      { num: 17, value: "foo" },
      { num: 18, value: "bar" },
      { num: 19, value: "test" },
      
      { num: 31, value: "one" },
      { num: 32, value: "two" },
      { num: 33, value: "three" },
      { num: 34, value: "four" },
      
      { num: 51, value: "apple" },
      { num: 52, value: "banana" },
      
      { num: 75, value: "alpha" },
      { num: 76, value: "beta" },
      { num: 77, value: "gamma" },
    ];

    const rearrangeData = (info) => {
      let output = [];
      info.forEach(item => {
        let len = output.length;
        if (len === 0 || output[len-1].val !== item.value) {
          output.push({start: item.num, end: item.num, val: item.value});
        } else output[len-1].end += 1;
      });
      return output;
    };

    console.log(rearrangeData(info));

Answer №2

If you're looking for a solution to your issue, consider utilizing a basic for loop.

const information = [
  { time: 31, length: 10 },
  { time: 32, length: 10 },
  { time: 33, length: 10 },
  { time: 34, length: 10 },
  { time: 35, length: 10 },

  { time: 68, length: 15 },
  { time: 69, length: 15 },
  { time: 70, length: 15 },
  { time: 71, length: 15 },

  { time: 80, length: 10 },
  { time: 81, length: 10 },

  { time: 98, length: 12 },
  { time: 99, length: 12 },
  { time: 100, length: 30 },
];
const toWindows = (arr) => {
  const result = [];
  let startingPoint = arr[0].time;
  let endingPoint = arr[0].time;
  let duration = arr[0].length;
  for (let i = 1; i < arr.length; i += 1) {
    if (
      arr[i].time - arr[i - 1].time === 1 &&
      arr[i].length === arr[i - 1].length
    ) {
      endingPoint = arr[i].time;
      duration = arr[i].length;
    } else {
      result.push({
        start: startingPoint,
        end: endingPoint,
        length: duration,
      });
      startingPoint = arr[i].time;
      endingPoint = arr[i].time;
      duration = arr[i].length;
    }
  }
  result.push({
    start: startingPoint,
    end: endingPoint,
    length: duration,
  });
  return result;
};

console.log(toWindows(information));

Answer №3

Here is a helpful technique:
Utilize the power of Optional chaining using ?. within an Array.reduceRight() function

const data = 
  [ { day:  31, length: 10 }, { day:  32, length: 10 }, { day:  33, length: 10 }, { day:  34, length: 10 }, { day:  35, length: 10 } 
  , { day:  68, length: 15 }, { day:  69, length: 15 }, { day:  70, length: 15 }, { day:  71, length: 15 } 
  , { day:  80, length: 10 }, { day:  81, length: 10 } 
  , { day:  98, length: 12 }, { day:  99, length: 12 } 
  , { day: 100, length: 30 } 
  ]

const convertToWindows = arr => 
  arr.reduceRight((acc,{day, length}) =>
    {
    if (acc[0]?.start===(day+1) 
     && acc[0]?.length===length)
      {
      acc[0].start = day
      }
    else
      {
      acc.unshift({start:day, end:day, length})
      }
    return acc
    }
  ,[])
  ;
console.log( convertToWindows(data) )
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Updating from React 17 to React 18 in Typescript? The Children of ReactNode type no longer supports inline conditional rendering of `void`

When using the React.ReactNode type for children, inline conditional renders can cause failures. Currently, I am utilizing SWR to fetch data which is resulting in an error message like this: Type 'false | void | Element | undefined' is not assig ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

Developing Angular2 applications in Visual Studio Team Services (formerly known as Visual Studio Online)

Currently, I have an angular2 client integrated into a Visual Studio vNext (ASP.Net 5) project. During my attempt to create a build in Visual Studio Team Services, I encountered errors similar to this one during the build step: It appears that module &a ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

JavaScript for rotating an element upon button click

My webpage design <div id="yabanner"> <img src="img/ok.jpg"> </div> <button>Click Me</button> <button>Click Me</button> <button>Click Me</button> My script code var button = document.getElementsBy ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

What is the best way to deploy a Vue Webpack application using Sails.js?

I am currently managing a Sails.js server alongside a Vue Webpack application, running as separate entities. Here's how my folder structure is laid out: /application-root/server/ /application-root/client/ Within the /server/ directory lies my Sails ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

What is the best way to simulate a service that returns a promise when writing unit tests for AngularJS using Jasmine?

I have a service named myService that relies on another service called myOtherService. The latter makes a remote call and returns a promise. Here's the implementation: angular.module('app.myService', ['app.myOtherService']) .fac ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Adding information to an array within a document in a MongoDB database

I am facing an issue where I am trying to add data to the readBook array in my User collection document. The code and console.log seem to indicate that the User is retrieved from the database and there is data to push, but nothing changes after the code ex ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

Bidirectional data binding in Angular 2 allows for communication between parent components and directives

Update: Experimenting with Angular2 Beta, I am working on incorporating an "editor" component template that includes a directive wrapping the Ace editor. In this scenario, the "editor" component acts as the parent of the Ace wrapper directive, and my goal ...

AngularJS - Shared service object mistakenly removed in error

When I call the removeQuestion() function for the second time, 2 questions are being deleted instead of one. Any suggestions on what might be causing this issue? Let me know if you require additional code snippets. controller.js crtPromoCtrl.controller(& ...

Tips for implementing dependency injection in AngularJs with ES6

I have integrated the yeoman angular-fullstack boilerplate into my project. 'use strict'; class LoginController { // Implementing login functionality. } angular.module('myApp') .controller('LoginController', LoginCont ...

Ensure exclusive access to variables for sequential updates in jQuery or JavaScript

I am currently developing a series of small functions in jQuery aimed at tracking how long it takes for a user to complete a form. The form consists of various input types and 'continue' buttons located within the form itself. Below are some sa ...