Loop through an array to find the average values of different segments within the array

I am currently working with an array structured like this:

["2011-06-16 16:37:20",23.2],
["2011-06-21 16:37:20",35.6],
["2011-06-26 16:37:20",41.8],
["2011-07-01 16:37:20",25],
["2011-07-06 16:37:20",22.8],
["2011-07-11 16:37:20",36.4],
["2011-07-16 16:37:20",34],
["2011-07-21 16:37:20",20]
[...]

Format: [$date,count]

My task now is to enhance each element of the array with a 3rd and 4th value, which are calculated as averages of N counts before or after.

For instance, when N=3

The 3rd value should be the average of the 3 count-values preceding, and the 4th value should be the average of the 3 count-values succeeding the current array element. The resulting array will look like this:

["2011-06-16 16:37:20",23.2, null,  34.13],
["2011-06-21 16:37:20",35.6, null,  29.86],
["2011-06-26 16:37:20",41.8, null,  28.06],
["2011-07-01 16:37:20",25,   33.53, 31.06],
["2011-07-06 16:37:20",22.8, 34.13, 30.13],
["2011-07-11 16:37:20",36.4, 29.86, null],
["2011-07-16 16:37:20",34,   28.06, null],
["2011-07-21 16:37:20",20,   31.06, null]

The null value is a placeholder for cases where averages cannot be calculated due to insufficient data points. In such cases, the average of all available counts can be displayed instead, like "24.4" (23.2+35.6)/2 for the 3rd line instead of null:

["2011-06-26 16:37:20",41.8, 24.4,  28.06],

I am struggling with writing the code to accomplish this task.

I would greatly appreciate any hints or assistance provided. Thank you.

//Update: I apologize for the inconvenience, but could someone please clarify why this question has received 2 downvotes? I am unsure of the reason and would appreciate feedback if I have made a mistake. Sorry for any confusion caused!

Answer №1

This code demonstrates a solution using a combination of higher-order functions:

var dates = [
    ["2011-06-16 16:37:20", 23.2],
    ["2011-06-21 16:37:20", 35.6],
    ["2011-06-26 16:37:20", 41.8],
    ["2011-07-01 16:37:20", 25],
    ["2011-07-06 16:37:20", 22.8],
    ["2011-07-11 16:37:20", 36.4],
    ["2011-07-16 16:37:20", 34],
    ["2011-07-21 16:37:20", 20]];

function calculateAverage(array) {
    return (array.reduce(function(accumulator, element, index) {
        return element + accumulator;
    }, 0) / array.length).toFixed(2) * 1;
}

function manipulateData(accumulator, element, index, array) {
    element.push((accumulator.length >= 3) ? calculateAverage(accumulator) : null);
    accumulator[index % 3] = element[1];
    return accumulator;
}

dates.reduce(manipulateData, []);
dates.reverse().reduce(manipulateData, []);
dates.reverse();

Output:

[["2011-06-16 16:37:20", 23.2, null, 34.13], 
 ["2011-06-21 16:37:20", 35.6, null, 29.87], 
 ["2011-06-26 16:37:20", 41.8, null, 28.07], 
 ["2011-07-01 16:37:20", 25, 33.53, 31.07], 
 ["2011-07-06 16:37:20", 22.8, 34.13, 30.13], 
 ["2011-07-11 16:37:20", 36.4, 29.87, null], 
 ["2011-07-16 16:37:20", 34, 28.07, null], 
 ["2011-07-21 16:37:20", 20, 31.07, null]]

Answer №2

data = [
    ["2011-06-16 16:37:20",23.2],
["2011-06-21 16:37:20",35.6],
["2011-06-26 16:37:20",41.8],
["2011-07-01 16:37:20",25],
["2011-07-06 16:37:20",22.8],
["2011-07-11 16:37:20",36.4],
["2011-07-16 16:37:20",34],
["2011-07-21 16:37:20",20]
];
data.forEach(function(el,i,arr){
    var x=null,y=null;
    if(i > 2){
        x = (arr[i-3][1] + arr[i-2][1] + arr[i-1][1]) / 3;
        x = x.toPrecision(x.toString().indexOf('.') != -1 ? 2+x.toString().indexOf('.') : x.toString().length);
    }
    if(i < arr.length - 3){
        y = (arr[i+3][1] + arr[i+2][1] + arr[i+1][1]) / 3;
        y.toPrecision(y.toString().indexOf('.') != -1 ? 2+y.toString().indexOf('.') : y.toString().length);
    }
    el.push(x);
    el.push(y);
});

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 best way to enable a disabled MUI MenuItem within a table that is being mapped, based on a specific item in the

In my table, I have a mapped object of users: {users.map((user,index) => { <TableRow key={index}> ... The final cell in the table contains a button that is linked to an MUI Menu. One of the menu items should be disabled if a specific aspect of ...

Strategies for Synchronizing Multiple Asynchronous Calls in NodeJS

I have a function getAliasesByRoleDetailed(role) that is responsible for retrieving user data based on a given role. This particular function utilizes axios to fetch the necessary data. The result obtained from executing this function appears in the follo ...

How to set cells to plain text in google sheets

I've been grappling with a formatting issue that I'm hoping someone can assist me with. In my script, there's a point where I need to combine the date value (e.g., 11/20/2020) from one column with the time (3:00 PM) from another column. This ...

Canvas - Occasionally, using lineTo() can result in crisp edges in the drawing

I've created a simple Canvas drawing app. However, I've noticed that occasionally the lineTo() command generates a line with fewer coordinates, resulting in many edges: I'm currently using the latest version of Firefox - could this issue be ...

Using identical variable names for functions in Node.js

I'm feeling a bit puzzled about the following code snippet. Is it possible to create a class in JavaScript like this? module.exports = function testName(params){ testName.test = function(req, res){ //some code here } return testName; } Inste ...

Is there a way for me to extract a sub-object from a larger object, utilize it as the data for multiple instances of a single controller, and ensure that all instances remain synchronized?

Sorry for any confusion in the question :-P I am working with a single JavaScript object that contains all the data for my application. I have a controller that will be used multiple times throughout the app, all working with the same data added through a ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

Search for elements once they have been dynamically loaded using AJAX with the

I have a function called getItemID which searches for all the IDs under a specific parent ID (#search-output). This function works well when the ID (#test) is already loaded when the page loads. However, I am dynamically generating these IDs (#test) using ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

Display the list items when the page first loads

I currently have this code snippet: <nav> <ul class="sel"> <li> <a href="#LINK1" data-title="A">A</a> </li> <li> <a href ...

Iterate through the elements in an array in order to generate new elements

Currently, I am in the process of comparing various popular javascript frameworks and I need to generate an HTML element for each object retrieved from an API. const frameworks = [ { name: "angular" }, { name: "ember" }, { name: "rea ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

Retrieving JSON data from an API's array

Encountering a minor JSON dilemma, I am trying to access the translations data in the API using this endpoint . However, I am struggling with retrieving the desired information. results = data.results; var li= ''; for (const x of results) { l ...

The Material UI Icon rendered using document.createElementNS in React is failing to load properly

I'm currently developing a tags section for my app, similar to the tags feature in a new Stack Overflow question form. For this, I am utilizing the Material UI close icon. You can see how it is implemented in this tutorial on YouTube. (I have confirme ...

Utilizing Vanilla JavaScript to Insert a Class When a Distinct Class Exists Within an Element

My goal is to dynamically add a class to specific elements based on the presence of another class in elements below them. Consider the following code snippet: < p class="my-paragraph">This is a sentence.</p> < p class="my-par ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Step-by-step guide to inserting an image into a Table Cell

I want to include my PDF image at the conclusion of the text in my table cell When it comes to my Table, I'm hoping that the image can be combined with the text seamlessly after it finishes <TableCell component="th" scope="row" className = {class ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Schedule Master: A sophisticated tool for time management

I have been following the instructions to implement a date time picker from this tutorial. I downloaded the necessary js and css files and placed them in the respective directories. However, when I click on the calendar icon, the calendar does not pop up. ...