What is the best way to determine the total number of hours?

I am currently working on a task that involves calculating the total number of hours from an array. Within this array, there are various sessions each with their own time frame for completion. The challenge I face is that the hour values are stored as strings.

Here is an example of how the data is structured:

[
    { "id": 1,
    "exercise": "1.1",
    "name": "Session one",
    "hours": "1"
    },
    { "id": 2,
    "exercise": "1.2",
    "name": "Session two",
    "hours": "4"
    },
    { "id": 3,
    "exercise": "1.3",
    "name": "Session three",
    "hours": "0,5"
    }
]

The desired total should be 5.5 hours in this case.

I have attempted to filter out the array like so:

 computed: {
    hours() {
        var hours = 0;
        this.data.filter((item => {
            hours += item.hours;
        }));
        return hours;
    }
},

However, the result returned is unexpectedly high.

Answer №1

After analyzing your input, I noticed that the id "3 hours" could not be converted into a number due to the way it is formatted. It should be represented as 0.5 instead of 0,5. If you are looking to calculate the total number of hours and filtering is not the appropriate method for obtaining a single value from a given array, you should consider using the reduce function. The code example would look something like this:

hours()
{
    return this.arr.reduce((acc, curr) => {
        acc = acc + +curr.hours;
        return acc;
    }, 0);
},

The correct implementation allows you to accurately sum up the hours in the array.

Answer №2

Utilizing the reduce method is the way to go!

Keep in mind that 0,5 is not a valid number, so you'll need to substitute , with . to ensure proper parsing.

const data= [

    { "id": 1,
    "exercise": "1.1",
    "name": "Session one",
    "hours": "1"
    },
    { "id": 2,
    "exercise": "1.2",
    "name": "Session two",
    "hours": "4"
    },
    { "id": 3,
    "exercise": "1.3",
    "name": "Session three",
    "hours": "0,5"
    }
]


const total = data.reduce((res, {hours}) => res + parseFloat(hours.replace(',', '.')), 0.)

console.log(total)

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

Injecting components into the DOM using JavaScript in Vue.js

I am currently developing a GUI for a webgame using Vue.JS and opting to use http-vue-loader instead of Webpack or similar tools. Personally, I find them cumbersome and prefer to avoid using them. Typically, in order to integrate my components into the DO ...

Calculate sums in ReactJS without the need for a button

Adding a few numbers might seem like an easy task, but I've been unable to do so without using an explicit button. // Using useState to handle state changes const [ totalCount, setTotalCount ] = useState(0) // Function to add numbers of differ ...

Prevent screen from loading without JavaScript using an overlay

Is there a way to darken and lock the page, preventing clicking or scrolling, while displaying white text notifying the user that JavaScript is not enabled? I understand that the recommended approach is to gracefully degrade all elements when JavaScript i ...

Generating objects with Sails.js - diving into nested creations

Currently, I have a controller set up to handle an API call /task/:id/start. Within this controller method, the first step is to validate if the Task with the specified ID is valid. If it is determined to be valid, then I need to proceed by creating two ot ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

What is causing my jQuery to function within the HTML document but not when linked externally?

I've been experimenting with AJAX implementation by working on a jQuery example located at static/js/form.js (function ($, window, document) { /* globals window, jQuery, document, console */ // Uncomment the return statement below to disable Ajax ...

Create an interactive popup window within a data table using Vuetify to enhance user experience

I currently have a datatable that contains numerous columns. My goal is to only display a select few columns in the datatable, while providing the remaining data in a modal/dialog when the user clicks on the "More" link within the row. Below you will find ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...

Attempting to execute an onclick event by clicking on a link is not functioning properly

Hello there, I created an HTML link <a href="javascript:void(0);" onClick="next(1)" id="next"></a> When I click on it, nothing happens. Using href="#" doesn't work either. Strangely, if I call next(1) in the console, it works. ...

Utilize useNavigate() in React to redirect users following form validation and submission, implementing routing alongside a loader and defined action

Recently, I created a demo site that features a form for submitting new user information. The following are the key files: App.jsx: import React from 'react'; import './App.css'; import { RouterProvider, createBrowserRouter } from ...

The utilization of awaitZip while developing with Express is overlooked by Node.js

I am working on a task to retrieve icon PNGs from gridfs in our mongodb database using mongoose. These icons need to be compressed into a zip file and served at a specific endpoint. Here is the code I have so far: var zip = require("node-native-zip"); as ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

What causes the tweets' IDs to be altered by axios when parsing the response from the Twitter search API?

I am currently utilizing axios to send a GET request to the Twitter search API in order to fetch recent tweets that utilize a specific hashtag. To begin with, I ran tests on the twitter search API via Postman and noticed that the id and id_str tweet statu ...

Storing data from PHP in Local Storage using JavaScript variable

When a specific build name is clicked, the inner HTML content is captured and assigned to a JavaScript variable called loadDump. This variable is then sent over to PHP via an AJAX request. $.ajax({ url:"http://custom-assembly.tcad.co.uk/wp-content/t ...

Steps to Resolve the Issue: "SyntaxError: Identifier 'getScrollParents' has already been declared; Bootstrap tooltips depend on Tether;"

After trying to resolve the issue by installing tether.js and utils.js, I found that fixing one error only led to two more popping up. Although I came across a similar post, my current issue is slightly different as it stemmed from a previous problem. Sh ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

How can an HTML5 application be configured to enable access to intranet and local files?

It's a known fact that accessing the local path of a file added using a file input field or drag-and-drop is not possible even with the new FileAPI. Whether this limitation is good, bad, or ugly is not up for debate. The FileAPI specs clearly state th ...

Discovering terms in JavaScript

Looking at a sorted array like this: var arr = [ "aasd","march","mazz" ,"xav" ]; If I'm searching for the first occurrence of a letter that starts with "m", how can I achieve it without iterating through the entire array? ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...