Combining array objects in JavaScript based on a matching condition

Is there a way to combine objects in an array if a specific condition is met? Specifically, I need to merge the start time and end time from objects in the array.

Here is an example array:

  [
      {id: 909, room: "room1", name: "end", timestamp: '10:00'}, 
      {id: 908, room: "room1", name: "start", timestamp: '09:00'}, 
      {id: 907, room: "room1", name: "end", timestamp: '08:00'}, 
      {id: 906, room: "room1", name: "start", timestamp: '07:00'}, 
  ]

From the above array, I want to pair up the objects where name: "end" is followed by name:start. The resulting array should be:

    [
        {room: "room1", endTimestamp: '10:00', startTimetamp: '09:00'}, 
        {room: "room1", endTimestamp: '08:00', startTimetamp: '07:00'}, 
      
    ]

There may be cases where the array starts with name:start and doesn't have its end time yet, like this:

  [
      {id: 910, room: "room1", name: "start", timestamp: '11:00'}, 
      {id: 909, room: "room1", name: "end", timestamp: '10:00'}, 
      {id: 908, room: "room1", name: "start", timestamp: '09:00'}, 
      {id: 907, room: "room1", name: "end", timestamp: '08:00'}, 
      {id: 906, room: "room1", name: "start", timestamp: '07:00'}, 
  ]

In this case, the resulting array should be:

    [
        { room: "room1", endTimestamp: null, startTimetamp: '11:00'},
        { room: "room1", endTimestamp: '10:00', startTimetamp: '09:00'}, 
        { room: "room1", endTimestamp: '08:00', startTimetamp: '07:00'}, 
    ]

Appreciate your help!

Answer №1

Here is a straightforward approach to solving this problem:

To begin, create an empty array called ResultArray:

const InputArray = [/*place your array values here*/];
const ResultArray = [];

Next, iterate through the InputArray and identify "start" rows to generate a corresponding ResultRow for each one:

for( let i=0 ; i < InputArray.length ; i++ ) {
    if( InputArray[i].name !== 'start' )
        continue;
  
    const ResultRow = {
        room: InputArray[i].room, 
        startTimetamp: InputArray[i].timestamp, 
        endTimetamp: null
    };

    // check the previous index
    if( i-1 >= 0 ) 
        if( InputArray[i-1].name === 'end' )
            if( InputArray[i].room === InputArray[i-1].room )
                ResultRow.endTimestamp = InputArray[i-1].timestamp ;

    ResultArray.push(ResultRow);
}

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

Using a JavaScript code to integrate data input and dropdown menu selections

I am currently working on a data input section on my website. Users will need to enter their name in a text field and then select either "Yes" or "No" from a dropdown menu. Once they click on the 'Generate' button, all the information along with ...

Utilizing worldwide server session within an express node.js application

What is the best way to grant access to the current session for the modules in my node.js app when I can only access it within the request's function? My app is complex but modular, and passing the session between modules seems challenging as it wou ...

What's the best way to set up server-side pagination for mui-datatable?

Is server-side pagination for mui-datatable implementation a complex task? Challenges: I am facing difficulties in capturing the user-selected value from the rowsPerPage options. When a user selects '15', how can I update these values within ...

JavaScript: Deactivate radio buttons based on selected value

Utilizing radio buttons to schedule appointments in a PHP web application is my goal. Presented below is a selection of Radio Buttons, from which the user can pick one. The selected value will be stored in the database as an appointment date and time. &l ...

Troubleshooting Problem with NodeJS Https.request

Attempting to create a test post for the Zip API: Zip Api Here is the JSON data posted, following Zip Pay's example - { "shopper": { "title": "Mr", "first_name": "John", "last_name ...

Animating a vertical line moving gracefully between two points

I am facing a challenge that requires your expertise. You may have come across an animated line resembling a scanner in various applications. I need something similar, but in the form of a graph. Specifically, I am looking to create a vertical line that a ...

Unable to create follow/unfollow feature with jquery ajax

Issue: While the database part for following and unfollowing actions is functioning correctly, there seems to be a problem with the jQuery and Ajax section. The follow button changes to unfollow (with some CSS styling) only after refreshing the page, rathe ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Is it possible to utilize md-select from Angular Materials to execute a function?

Encountering a peculiar issue with the md-select element - I may be using it incorrectly. The goal is to redirect to a new page or sign out based on the selected option, but instead, I'm faced with this error: Error: Failed to execute 'removeChi ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

Performing an HTTP request to itself in NodeJS/ExpressJS

Currently coding an NPM module that requires making an HTTP request to itself, which is the running web server. Here's an example: let url = "http://127.0.0.1:" + (process.env.PORT || 3000) + path; request(url, function(error, response, body){ ... ...

SEO Friendly URL for JQuery Tabbed Content

I have developed a jQuery powered tabbed content system, where clicking on a tab changes the content below. However, I am facing an SEO issue. The SEO specialist has advised me to make it more SEO-friendly by adding different URLs to each tab. Can anyone ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

What is the best way to alternate between two CSS stylesheets when using jQuery-UI?

Just getting started with jQuery and javascript and decided to test out 2 different jQuery-ui stylesheets in a simple .html file. The goal is to have the example dialog open with the "flick" stylesheet and the datepicker within the dialog open with the "u ...

Guide to setting up Mongodb with mongoose in the latest Next.js 13.3 update

I'm having trouble connecting MongoDB with Mongoose in Next.js 13.3 Version. I keep getting errors when trying to import the connectDb file or UserSchema file in api/getProducts/route.js file. Can someone please help me with step-by-step instructions ...

Modifying data on the fly for a Highcharts series

My chart is currently functioning well with data in the options. However, when I leave the data empty for a series and attempt the following code (in order to change the data based on a click event), it fails to work. Any suggestions on how I can rectify ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...

Activate JavaScript when FullCalendar detects an event overlap

Can anyone help with triggering a JavaScript function when two events overlap? I've searched online but can't seem to find a way to detect this overlap. Any assistance would be much appreciated. ...

Tips for transferring data from one tab to another tab using Greasemonkey

Is it possible to extract data from a webpage in one tab and then input it into a textarea on a different page opened in a separate browser tab using Javascript and Greasemonkey? ...