Using the reduce method in a different function with JavaScript

Is there a way to filter out duplicates from the data parsed from my JSON file using the reduce function and make it accessible by calling the getFilteredData() function?

async function getFilteredData() {
        return new Promise((resolve) => {
          oWebViewInterface.on("loadData", function (data) {
            var thresholdValues = data.monitor;
            var filteredData = data.data.reduce((arr, d) => {
              if (arr.find((i) => i.timestamp === d.timestamp)) {
                return arr;
              } else {
                return [...arr, d];
              }
            }, []);
            resolve(filteredData); // resolve the promise with the filtered data
            //can I do: resolve(filteredData, thresholdValues) to resolve both?
          });
        });
      }

However, implementing this approach leads to an error message "Uncaught TypeError: Cannot read property '0' of undefined" for the last two console.log(), while the first one works correctly and logs the expected value.

Answer №1

The most straightforward approach is to utilize a Promise along with async/await. Wrap your asynchronous call in a Promise and await it on the client side:

async function getFilteredData() {
    return new Promise( resolve => {
        oWebViewInterface.on("loadData", function (data) {
          var monitorData = JSON.parse(data).reduce((arr, d) => {
            if (arr.find((i) => i.zeitstempel === d.zeitstempel)) {
              return arr;
            } else {
              return [...arr, d];
            }
          }, []);
          resolve(monitorData); // resolve the promise with the data
        });
    });
}

Then, when you make the call, simply use await:

var filteredData = await getFilteredData();
console.log(filteredData[0].id);

Edit: Based on your comments, I noticed that you are calling getFilteredData twice in your code - this can lead to inefficiencies. Make sure to call it only once. You can simplify this process by creating a separate async method for configuring your chart:

async function configChart(){
      var data = await getFilteredData();
      var werteArr = [];
      var zsArr = [];
      for (i = 0; i < data.length; i++) {
         werteArr.push(data[i].wert);
         zsArr.push(data[i].zeitstempel);
      }
        

      //defining config for chart.js
      var config = {
        type: "line",
        data: {
          labels: zsArr ,
          datasets: {
            data: werteArr,
            // backgroundcolor: rgba(182,192,15,1),
          },
        },
        // -- snip rest of config -- //
     }
     var ctx = document.getElementById("canvas").getContext("2d");
     window.line_chart = new window.Chart(ctx, config);
}

window.onload = function () {
    configChart(); // no need to await this. It'll happen asynchronously
};

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

The mysterious attribute of "undefined" in React (Redux)

I encountered an issue with an undefined property while attempting to add a product to the cart in React with Redux. It's puzzling because I have a similar action for adding to Favorites that works without any errors. The specific error message points ...

When attempting to retrieve a JSON object in xCode, it consistently results in a nil value

Currently, I am facing an issue with establishing a JSON connection with my SQL database. When I directly test the PHP file, it works perfectly by both writing to and retrieving data from the database. However, when I try to retrieve the JSON object using ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Creating a custom service that utilizes $cacheFactory

Utilizing $cacheFactory to store configurations and user data for one-time retrieval: var cache = $cacheFactory("Temp"); var getCachedData = function (url) { var data = cache.get(url); var deferred = $q.defer(); if (data) { ...

The jQuery plugin for mmenu does not activate the selected menu item

I recently implemented a jQuery menu plugin that I found on Overall, everything is functioning correctly. However, I am encountering an issue where the active state is not displayed when selecting a sub menu. Instead, it keeps redirecting to the main page ...

Access licensedContent property on YouTube API using PHP

Trying to improve the consistency of music search results on the Youtube API, I decided to categorize content into licensed and non-licensed. Here is the Json response from the API call: { "kind": "youtube#videoListResponse", "etag": "\"XI7nbFXulY ...

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

Issue encountered when concealing page elements followed by revealing them again

My goal is to conceal an id within a page and then reveal it once all the JavaScript has finished loading on the page. The JavaScript I am using to display the content again is: $(document).ready(function() { $("#HomePage")[0].style.visibility = "visib ...

Difficulty in altering the background of an input box

I am attempting to design a textbox that changes its background color to green when the correct answer is submitted, and to red for an incorrect answer. Unfortunately, nothing is happening for either option. document.querySelector('form').addE ...

What is causing the malfunction in jQuery version 1.7.x?

Here is a code snippet demonstrating the issue I am facing: var $div = $('<div>'); $('span').live('click', function() { this.innerHTML = 'changed'; }); $div.append( $('<span>span</span>& ...

What is preventing the darkBaseTheme from being applied in material-ui?

import React from 'react'; import ReactDOM from 'react-dom'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMui ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

Tips on showcasing array elements within a table's tbody section and including several values within the same array

I am struggling to figure out how to display array values in my table rows that I receive from input values. I have created an array, but I can't seem to find a way to display them in the table. Furthermore, I want to be able to add more values to th ...

Apply a class to each element that contains the specified name attribute

I have successfully implemented a prices tab on the top of my page, with tabs for different packages at the bottom. When a user selects a certain package, only specific items from the list are visible while the others are hidden. I managed to streamline ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

If an element contains a specific class, then set its display property to none

I am attempting to utilize the hasClass method in JavaScript to determine whether a div should be hidden (display: none) or kept visible as usual. Below is the snippet of code I currently have: if (!$('cool').hasClass('hot')) { ...

What could be causing the promises in Promise.all to remain in a pending state?

After restructuring my code to correctly utilize promises, I encountered a challenge with ensuring that the lastStep function can access both the HTML and URL of each page. To overcome this issue, I'm attempting to return an object in nextStep(). Alt ...

I'm looking to center the map based on latitude and longitude data retrieved from a JSON file. Additionally, I want to implement functionality in vueJS that displays a popup with a name when a marker is clicked

Here is my VueJS script that fetches JSON data and displays a map: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id ...

Making modifications to the json file in the internal storage results in the removal

I am facing an issue while trying to update a single value in my json file stored internally. Despite having 222 objects in the json, all of them except one get deleted when I attempt to make the change. Can anyone provide insights into why this might be h ...