How can objects be merged within an array and a new object be inserted?

I have an array of objects representing podcasts in a podcast app. Here is how the data looks:

[{ id: "uuid-1"
   timeInSeconds: 1000
   dateListened: "2021-01-01T15:57:17.000Z" }, // <---same day
{  id: "uuid-2"
   timeInSeconds: 4900
   dateListened: "2021-01-01T16:57:17.000Z" }, // <---same day 
{  id: "uuid-3"
   timeInSeconds: 3200
   dateListened: "2021-09-01T16:57:17.000Z" }, 
{  id: "uuid-4"
   timeInSeconds: 6000
   dateListened: "2021-10-01T16:57:17.000Z" } ]

I am looking to create a function that can combine the activity times if the dateListened falls on the same day. The desired output should resemble this:

[{ id: "uuid-new" 
   timeInSeconds: 5900 // <---- combined seconds listened on Jan 1
   dateListened: "2021-01-01T15:57:17.000Z" },
{  id: "uuid-3"
   timeInSeconds: 3200
   dateListened: "2021-09-01T16:57:17.000Z" }, 
{  id: "uuid-4"
   timeInSeconds: 6000
   dateListened: "2021-10-01T16:57:17.000Z" } ]

I've tried using a .map() function with a nested .some() but I haven't been successful yet. If anyone has any hints or suggestions on what approach I should take next, I would appreciate it. Thank you!

Answer №1

To simplify the process, you can reduce the number of items and map them to a date key, then extract the values and transform them into individual objects.

Here are the key elements to focus on:

let date = new Date(info.dateListened).toLocaleDateString('en-US')

const data = [
  { id: "uuid-1",
    timeInSeconds: 1000,
    dateListened: "2021-01-01T15:57:17.000Z" }, // <---same day
  { id: "uuid-2",
    timeInSeconds: 4900,
    dateListened: "2021-01-01T16:57:17.000Z" }, // <---same day 
  { id: "uuid-3",
    timeInSeconds: 3200,
    dateListened: "2021-09-01T16:57:17.000Z" }, 
  { id: "uuid-4",
    timeInSeconds: 6000,
    dateListened: "2021-10-01T16:57:17.000Z" }
 ];

const result = Object
  .values(data.reduce((acc, info) =>
    (date =>
      ({ ...acc, [date]: [...(acc[date] || []), info ] }))
    (new Date(info.dateListened).toLocaleDateString('en-US')), {}))
  .map(value => value.length === 1 ? value : {
    id: 'uuid-new',
    timeInSeconds: value.reduce((sum, { timeInSeconds }) => sum + timeInSeconds, 0),
    dateListened: value[0].dateListened
  });

console.log(result);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Answer №2

To achieve the desired outcome, utilize the reduce method and only include the timeInSeconds if the year, month, and date match exactly.

const arr = [
  {
    id: "uuid-1",
    timeInSeconds: 1000,
    dateListened: "2021-01-01T15:57:17.000Z",
  },
  {
    id: "uuid-2",
    timeInSeconds: 4900,
    dateListened: "2021-01-01T16:57:17.000Z",
  },
  {
    id: "uuid-3",
    timeInSeconds: 3200,
    dateListened: "2021-09-01T16:57:17.000Z",
  },
  {
    id: "uuid-4",
    timeInSeconds: 6000,
    dateListened: "2021-10-01T16:57:17.000Z",
  },
];

const result = arr.reduce((acc, curr) => {
  const { id, timeInSeconds, dateListened } = curr;
  const searchSameDateElement = acc.find((o) => {
    const first = new Date(o.dateListened);
    const second = new Date(dateListened);
    const isYearSame = first.getFullYear() === second.getFullYear();
    const isMonthSame = first.getMonth() === second.getMonth();
    const isDateSame = first.getDate() === second.getDate();
    return isYearSame && isMonthSame && isDateSame;
  });
  if (!searchSameDateElement) {
    acc.push(curr);
  } else {
    searchSameDateElement.timeInSeconds += timeInSeconds;
  }
  return acc;
}, []);

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

Python and Javascript clashing with one another

(Updated question for clarity). I am currently developing a flask app game that involves users inputting guesses via the web browser. The backend, which runs on Python, checks these guesses and provides feedback to the user about their accuracy. Additional ...

What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer Here is how I've modified the last line: 1 bottle of beer on the wall, 1 bottle of beer. Take it down and pass it around, no more bottle of beer on the wall. How ...

Enhance Shipping Options on Your Woocommerce Cart

I am facing a challenge with providing delivery options for three different countries in my e-commerce store. I want the customer to be able to select their country and instantly see the available delivery methods without having to refresh the entire page ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

Invoking a Referenced Array with a Function Call

Having trouble with a function call for an array and encountering the error: cannot refer to template array without an argument list repeatedly. How can I efficiently pass this array by reference to the main function? using namespace std; //function pr ...

Change the color of specific elements in an SVG using React

Can I change the dynamic primary color from ReactJS to a specific class in an SVG file? If yes, how can it be done? Error.svg <!-- Generator: Adobe Illustrator 26.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1&qu ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

A guide on installing a npm dependency module from a local registry domain

I have successfully published a module on my own custom registry domain, located at , and I am able to publish updates to the module there. Unfortunately, I am encountering an issue with dependencies within my published module. For example: "dependencies" ...

Activating the loader dismiss command will transition the swiper to the current page

Having a swiper and loader makes the scenario very straightforward. The loader is initialized whenever calculations are performed, and after successfully obtaining the result, the loader turns off and swipes to the second slide. <swiper-container #sl ...

Retrieving individual data elements from an array with the help of the .find() method

I am struggling to display specific details of an object within an array by using .find() method, but I keep receiving undefined as the output. Below is the code snippet where I attempted this, when I log the ID, I can see a value, however, when I try to ...

What could be the reason for the data showing up only within a foreach loop but turning into a non-object outside of it?

I am a beginner in PHP and feeling confused about a certain aspect... When I use the following code, it displays the data: <?php foreach ($profile as $p):?> <?php echo $profile->custom_url;?> <?php endforeach?> ...

"Using angularjs's $location.search method results in an empty object being

I am trying to retrieve my URL querystring in AngularJS using the $location service, similar to this example. My URL looks like this - http://someDomain.com/create/index.jsp?queryToken=123abc However, in my directive: vm.queryParam = $location.search(); ...

What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){ $("#items").children().click(function(){ $(this).toggleClass('clicked'); }); }); .clicked { background-color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></s ...

Incorporating Microsoft's Emotion API into an HTML website

Currently, I am attempting to develop a HTML webpage that can detect emotions from images submitted by the user. By referring to Microsoft's documentation, I have produced the following HTML file: <!DOCTYPE html> <html> <head> & ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

In what way can the jQuery .each() function make use of the index as a variable?

Consider the jQuery .each() function, which comes with a useful feature. For example: $('.element').each(function(index){ console.log(index); }); Here, you can access the index of the currently selected element using the "index" variable. ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Retrieve the data attribute associated with the chosen dropdown selections

I'm currently facing an issue with assigning a custom data attribute to a select box option and then transferring that value to a hidden form field. Here is the HTML I am working with: <select id="sampleorder" multiple="multiple"> <option ...