Generate a fresh array consisting of unique dates

As I navigate through various arrays to gather data, I encountered a hurdle. My task is to determine the number of days spent in each city. The challenge lies in counting time entries that occur within the same day as just one day. For example, in the given data set, the first two entries for San Diego should be considered one day since they happened on the same day.

timeLogs = [
    {'city':'San Diego','date':'2017-03-21T18:52:00.984Z'},
    {'city':'San Diego','date':'2017-03-21T12:13:00.984Z'},
    {'city':'San Diego','date':'2017-03-19T11:02:00.984Z'},
    {'city':'Boulder','date':'2017-02-12T11:29:00.984Z'}
]

The desired output would be:

daysPerCity = [
    {'San Diego':'2'},
    {'Boulder':'1'}
]

I am currently working on a loop that converts dates to strings and checks for equality. If the dates are the same, I aim not to increment the city count in the new array. However, I'm facing an issue when dealing with the very first instance of a city...

Answer №1

Utilizing Array methods such as reduce and map can help construct an object that organizes unique days by city. By then employing Object.keys(...).length, you can determine the count of distinct days.

var timeLogs = [
    { city: 'San Diego', date: '2017-03-21T18:52:00.984Z' },
    { city: 'San Diego', date: '2017-03-21T12:13:00.984Z' },
    { city: 'San Diego', date: '2017-03-19T11:02:00.984Z' },
    { city: 'Boulder', date: '2017-02-12T11:29:00.984Z' }
]

var daysPerCity = timeLogs.reduce(function (map, e) {
  (map[e.city] = map[e.city] || {})[e.date.slice(0, 10)] = true
  return map
}, {})

Object.keys(daysPerCity).forEach(function (k) {
  this[k] = Object.keys(this[k]).length
}, daysPerCity)

console.log(daysPerCity)

Answer №2

If you're looking for a solution using ES6, consider the following code snippet:

const travelLogs = [
    {'city':'Los Angeles','date':'2018-04-15T10:30:00.984Z'},
    {'city':'Los Angeles','date':'2018-04-14T12:45:00.984Z'},
    {'city':'New York','date':'2018-03-25T08:20:00.984Z'},
    {'city':'Chicago','date':'2018-02-18T16:50:00.984Z'}
];

const summary = Object.assign({}, ...Array.from(
    travelLogs.reduce((acc, {city, date}) => {
        (acc.get(city) || acc.set(city, new Set).get(city))
            .add(date.substr(0, 10));
        return acc;
    }, new Map),
    ([city, days]) => ({ [city]: days.size })
));

console.log(summary);

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

Recursively mirroring the contents of a webpage following the execution of JavaScript code

My goal is to recursively mirror a webpage, meaning I want to retrieve all pages within that webpage. Since all the webpages are located in subfolders of one main folder, I thought I could easily accomplish this using wget: wget --mirror --recursive --pag ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...

Import HTML document into a Bootstrap Popup

Currently, I am working on creating a modal that loads content dynamically. Below is the JavaScript code I have been using for this task: function track(id,title) { $('#listenTrack').modal('show'); $('#listenTrack').f ...

Transform an array into JSON by utilizing a foreach loop

I have been attempting to convert an array into JSON format, but I am not achieving the exact result that I desire. Below is my code snippet: <?php $result=array(); $result['status']=1; $data=array( array(" ...

Alert: Jade has detected an unforeseen block called "scripts"

I created a jade file with the following content: extends layout block content h1= title p Hello and welcome to #{title} block scripts script(src='/socket.io/socket.io.js') script(src='/javascripts/client.js') But when I try ...

The array map is not displaying properly in the table

I am trying to map an array on my webpage and display the results in a table. However, I am facing an issue where the content is not showing up when I compile the page. Can someone please assist me with this problem? When I print the content of a variabl ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

Is it possible to edit the JSON file served by the API in NextJS during runtime and have the API serve the updated file?

I apologize for the wording of my question. My main struggle lies in not being able to articulate it properly, as I have searched extensively online without finding a solution. In my usage of api routes in Next.js, I am seeking to serve a data.json file. ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

Storing information in memory through the use of Javascript

i am interested in keeping this type of data consistently in memory. app_id admin_id url status 123 1 xyz.com 1 123 2 xyz.com 0 539 3 exmaple.com 1 876 4 new.com ...

What is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Transform SVG with a Click

Can someone assist me with rotating the pink area on click and moving it to a new angle from its current position? I am looking for a way to save the current position of the pink area and then, when clicked, move it smoothly to a new position. Your help ...

Using jQuery to control mouseenter and mouseleave events to block child elements and magnify images

My objective is to create a hover effect for images within specific div elements. The images should enlarge when the user hovers their mouse over the respective div element. I plan to achieve this by adding a child element inside each div element. When the ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

Encountering issues with HMR after relocating files to the /app directory

Greetings, I am currently in the process of learning how to utilize express with webpacks HMR feature. However, every time I make changes and save a file, I encounter the following error: "The following modules couldn't be hot updated: (Full reload n ...

Is it possible to use cakephp and AJAX to determine if a table is empty?

Is there a way to determine if a table is empty using CakePHP and AJAX? In my index.ctp, I have included an image that, when clicked, will notify the user about the status of the table. If the table is empty, an alert box will pop up; otherwise, the user w ...

Issue occurred while executing maildev - logger.info(`Shutdown signal received, beginning shutdown now...`)

After rebooting my machine, I encountered an error when running the maildev command in the terminal. Despite uninstalling and reinstalling the program, the issue persists. Below is the complete error message. Appreciate any help in solving this problem. ...

In React JS, you can assign an array of student IDs with Boolean values by creating a state variable to hold the values. When a button is clicked, you can toggle the Boolean value

Imagine a scenario where an API call returns an array of student IDs: [ { "id": 1, "name": "Thorsten", "isClicked": false }, { "id": 2, "name": "Daria", "isClicked": false }, { "id": 3, "name": "Elset", "isClic ...