What is the best way to transform the incoming data using JavaScript?

The data I have from Algolia in my project includes a seconds data presented as an array.

This is the method I use to extract the seconds data from Algolia:

@if(isset($content['length']))
<div class="flex items-center space-x-6">
   <div class="flex items-center">
      <img src="/assets/images/icon-clock-black.svg" alt="">
      <span  id="time" value="{{ $content['length'] }}" class="text-sm md:text-base leading-6 font-normal ml-1">{{ $content['length'] }}hrs</span>
   </div>
   <div class="flex items-center">
      <img src="/assets/images/icon-list-black.svg" alt="">
      <span  class="text-sm md:text-base leading-6 font-normal ml-1">{{ $content['lectures_count'] }} Lessons</span>
   </div>
</div>
@endif

In the above code snippet, the seconds data is extracted as {{ $content['length']}}.

The Algolia data is structured as follows, with the length value differing for each content:

{
  "id": 99,
  "user_id": 613,
  ... (other data fields) ...
  "length": 6783,
  ... (other data fields) ...
  "lectures_count": 27,
  ... (other data fields) ...
}

I attempted to create a JS code to display the length data in hour minute seconds format, but encountered issues. The code snippet is as follows:

@section('scripts')
    <script type="text/javascript">

        function secondsToHms(d) {
            var d = getElementById("time").value;
            var h = Math.floor(d / 3600);
            var m = Math.floor(d % 3600 / 60);
            var s = Math.floor(d % 3600 % 60);

            var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
            var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
            var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
            return hDisplay + mDisplay + sDisplay; 
        }

    </script>
@endsection

However, calling this function resulted in an error stating "call undefined function." Any assistance on resolving this issue would be greatly appreciated.

Answer №1

When looking at your secondsToHms function, there appears to be a small issue. You have defined a variable named d as a function parameter, but then you also declare another variable d in the line immediately following - this is not allowed in JavaScript. Fortunately, after testing the code, it seems to work as expected:

function secondsToHms(d) {
    var h = Math.floor(d / 3600);
    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
    var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
    return hDisplay + mDisplay + sDisplay; 
}

console.log(secondsToHms(500));
console.log(secondsToHms(5000));
console.log(secondsToHms(12571243));

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

What is the process for assigning a value to a property?

I am currently developing an Angular application that utilizes reactive forms. I need to retrieve the values of dynamically created fields within a form group. Here is the code I have implemented: this.formSaisieSecondary = this.fb.group({ ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

Is it necessary for me to authenticate jwt tokens?

Let me explain my situation. I have generated a JWT token and stored it in Redis with a TTL of 1 hour. Now, most tutorials suggest using jwt.verify to authenticate the token. I understand that jwt.verify is used to verify whether the token is authentic or ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

What is the best way to retrieve all collections and their respective documents in Firestore using cloud functions?

Seeking to retrieve an array structured as [1year, 1month, etc] with each containing arrays of documents. Currently encountering a challenge where the returned array is empty despite correct snapshot sizes. Unsure if issue lies with push() method implemen ...

What is the best way to create a function that will initiate the download of a particular file based on a specific key provided by the

I need assistance in creating a function for my text box and button setup. Can someone please guide me on how to achieve this? The user will be provided with a specific alphanumeric key from the website. They must input this key into the text box and then ...

Is there a way to prevent text flipping using CSS or jQuery?

Is there a way to prevent the contents of an object from flipping when it is rotated +180°? I want to keep everything inside readable and avoid any flipping effects. ...

The REST API for HTTP DELETE does not validate for null values

Currently facing an issue while developing a RESTful API for a web service. I am attempting to delete an email, but first I need to confirm if the email actually exists. The problem arises when it fails to check if the email is null and does not return a ...

alert message specific to a certain page (triggered by clicking the back button, accessing the menu, or pressing a particular button

I am facing a dilemma with a web application that allows the administrator (my client) to edit orders. They have expressed a need for warnings to prevent the loss of work. These warnings should trigger if you click on: Buttons such as Save, Work Order, D ...

Error: Trying to use 'search' before it has been initialized causes a ReferenceError

Every time I run my code, I encounter this reference error but I can't figure out what's causing it. ReferenceError: Cannot access 'search' before initialization App C:/Users/GS66/Desktop/IN20/IFN666/week4/src/App.js:60 57 | 58 | expor ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

Conceal certain values within an array

Scenario: Given an array: array([[1, 2, 0, 3, 4], [0, 4, 2, 1, 3], [4, 3, 2, 0, 1], [4, 2, 3, 0, 1], [1, 0, 2, 3, 4], [4, 3, 2, 0, 1]], dtype=int64) And a set of "bad" values: {2, 3} The objective is to generate a ma ...

What is the best way to implement asynchronous image loading on hover events in React.js?

You may have come across this type of effect before. A good example can be found here - https://codepen.io/anon/pen/GEmOQy However, I am looking to achieve the same effect in React. While I understand that I can use the componentDidMount method for AJAX c ...

Issues with scaling background videos in HTML5

I'm having trouble making a video scale properly with the browser window while still covering the entire area. Does anyone know why my current approach isn't working? HTML: <div class="bgVideoWrap"> <video id="bgVideo" loop="true" aut ...

Wave: clock strikes midnight

I have a data chart with the X-axis representing time. I want the ticks on the X-axis to be placed at 0:00 each day. This was working fine before I updated to the latest version of Flot. ... xaxis: { ticks: 6, mode:"time", timezone:<cfout ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Searching for a point within a specified range using Sequelize

I have a model called Location with a field named coordinates of type geometry. I'm looking to create a function that takes in latitude, longitude, and radius as parameters, and returns all locations within that radius (in meters). I attempted to foll ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

How come ngOnChange is unable to detect changes in @Input elements when ngOnDetect is able to do so?

Check out this plunker Please note: In order to see the effect, you need to restart the app after entering the link. import {Component, OnInit, Input, OnChanges, DoCheck} from 'angular2/core' @Component({ selector: 'sub', templat ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...