Guide on aggregating values of a specific property within an array of objects, considering a given condition

As a junior Web Developer seeking some guidance to solve a problem, I am reaching out here for the first time. Please bear with me if I miss any crucial details.

The data array I have looks like this:

[
 {x: Date(1234), y: 0}
 {x: Date(1235), y: 0}
 {x: Date(1236), y: 300}
 {x: Date(1237), y: 300}
 {x: Date(1238), y: 300}
 {x: Date(1239), y: 300}
 {x: Date(1240), y: 300}
 {x: Date(1241), y: 0}
 {x: Date(1242), y: 0}
 {x: Date(1243), y: 0}
]

I am looking to create a new array where consecutive 'y' values greater than 0 are summed up. The sum should be associated with the first 'x' value of the consecutive items, as shown below:

[
 {x: Date(1234), y: 0}
 {x: Date(1235), y: 0}
 {x: Date(1236), y: 1500}
 {x: Date(1241), y: 0}
 {x: Date(1242), y: 0}
 {x: Date(1243), y: 0}
]

I believe utilizing 'reduce' could help, but I am unsure about the exact steps to take. Any assistance on this matter would be highly appreciated.

Thank you in advance!

Answer №1

To achieve the desired result, you can utilize the reduce method in the following manner: https://jsbin.com/leladakiza/edit?js,console

var data = [
 {x: Date(1234), y: 0},
 {x: Date(1235), y: 0},
 {x: Date(1236), y: 300},
 {x: Date(1237), y: 300},
 {x: Date(1238), y: 300},
 {x: Date(1239), y: 300},
 {x: Date(1240), y: 300},
 {x: Date(1241), y: 0},
 {x: Date(1242), y: 0},
 {x: Date(1243), y: 0},
];

var result = data.reduce(function (accumulator, value) {
  var lastIndex = accumulator.length - 1;
  if (value.y <= 0 || lastIndex < 0 || accumulator[lastIndex].y <= 0) {
    accumulator.push(value);
  } else {
    accumulator[lastIndex].y += value.y;
  }
  return accumulator;
}, []);

Answer №2

One efficient way to handle this scenario is by utilizing a reduce function as shown below.

var arr = [{
    x: Date(1234),
    y: 0
  },
  {
    x: Date(1235),
    y: 0
  },
  {
    x: Date(1236),
    y: 300
  },
  {
    x: Date(1237),
    y: 300
  },
  {
    x: Date(1238),
    y: 300
  },
  {
    x: Date(1239),
    y: 300
  },
  {
    x: Date(1240),
    y: 300
  },
  {
    x: Date(1241),
    y: 0
  },
  {
    x: Date(1242),
    y: 0
  },
  {
    x: Date(1243),
    y: 0
  }
];

var yGreaterThanZero = null;
var aggregated = arr.reduce(function(acc, cur) {
  if (cur.y > 0) {
    if (!yGreaterThanZero) {
      acc.push(cur);
      yGreaterThanZero = cur;
    } else {
      yGreaterThanZero.y += cur.y;
    }
  } else {
    acc.push(cur);
  }
  return acc;
}, []);

console.log(aggregated);

Answer №3

This logic demonstrates an interesting approach. The process involves initiating recording when a value greater than 0 is detected and then concluding it at the end of the recording (when a value less than 0 appears).

var a = [
 {x: Date(1234), y: 0},
 {x: Date(1235), y: 0},
 {x: Date(1236), y: 300},
 {x: Date(1237), y: 300},
 {x: Date(1238), y: 300},
 {x: Date(1239), y: 300},
 {x: Date(1240), y: 300},
 {x: Date(1241), y: 0},
 {x: Date(1242), y: 0},
 {x: Date(1243), y: 0},
 {x: Date(1244), y: 200},
 {x: Date(1245), y: 200},
 {x: Date(1246), y: 200},
 {x: Date(1247), y: 200},
]

var newA = [];
var recording = false;
var temp = {}
a.forEach(item => {
  if (item.y > 0) {
    recording = true;
    if (temp.y) {
      if(!temp.x) temp.x = item.x;
      temp.y = temp.y + item.y
    } else {
      temp = item;
    }
  } else {
    if (recording) newA.push(temp)
    recording = false;
    temp = {};
    newA.push(item);
  }
})
if (recording) newA.push(temp)

console.log(newA)

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

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

Having trouble retrieving a customized header from the HTTP response

I've encountered an issue with my Node.js server where I set a custom header. I added the Access-Control-Expose-Headers to allow access from browsers, and it works fine in Chrome and Firefox. However, I'm getting an error in PhantomJS saying "Ref ...

Creating routes in Node.js after setting up middleware

Currently tackling a project using node.js and encountering a specific issue. After setting up all routes with express (app.get("..", func)), I find myself stuck with a middleware that catches all requests and redirects to a 404-page. The problem arises w ...

Tips for selecting an <select> option value based on an URL parameter automatically

I have a 2-step form where I am successfully passing the first name in the URL from step 1 to step 2, but I am struggling to do the same for a select field. Here's an example of what I have: In the URL: ?firstname=Bob Form Field: <input type= ...

Achieving Center Alignment for Material-UI's <Table> within a <div> using ReactJS

Currently, I am working with a Material-UI's <Table> embedded within a <div>. My goal is to center the <Table> while maintaining a fixed width. I want the table to remain centered in the browser, but if the browser window is minimize ...

Calculate the sum of hours worked in a day using pure JavaScript, no external libraries required

Hello, I'm new to this website and please excuse me if my English is not perfect, I am trying my best to communicate :) I have been working on a page that calculates the total hours worked in a day and this is what I have achieved so far until 15/06 ...

jQuery UI Autocomplete for web addresses

I am trying to implement instant search with jQuery UI autocomplete, and I want to be able to add a link that will be triggered when a result is clicked. Javascript $("#searchinput").autocomplete({ source: "search/get_searchdata", select:function ...

Is there a maximum size limit for the Fabric.js Path Array?

Has anyone tried plotting a line graph using Fabric.js and encountered issues with the fabric.Path? I've noticed that it stops drawing after 8 segments even though I have attempted different methods like loops and individually coding each segment. co ...

Why is the total from summing up the values in an array incorrect?

When I attempt to add the elements of an array using shared memory and two child processes, the output is incorrect and I encounter a segmentation fault. int main() { int a[100],i,k,s1=0,s2=0,lim=100; int status1,status2; pid_t pid1,pid2; int perm=S_IRWX ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

I'm working on updating a field within a Firestore document using ReactJS

I am encountering an issue while attempting to update a field within a document in Firestore using ReactJS. Interestingly, others have successfully done it without any errors. app.js const app = initializeApp(firebaseConfig); const auth = getAuth(app); co ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

Determine the associated value for a given key within a TypeScript object

I have a structure like this: type newsItem = { img: string; slug: newsSlug; text: newsText; }; derived from an enum like this: export const newsEnum = { interesting: "Interesting", regions: "Regions", contradictory: " ...

What is the process for importing npm scoped packages with @ symbol in Deno?

Having some trouble with importing @whiskeysockets/baileys in Deno. Here's the code snippet I'm using: import * as a from "npm:@whiskeysockets/baileys"; console.log(a); When I try to run deno run main.ts, it throws the following error: ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: https://i.sstatic.net/4b4Sm.png Below is the code snippet I use ...

Encountering problems when transforming Next.js server components into client components

I've been working on a blog site using next.js. Initially, I had a home page that was a server component, but I wanted to convert it into a client component to add interactivity like pagination. However, after converting the code to a client componen ...

Using jQuery sortable with the overflow property set to hidden to sort items between two lists

I need help with a jQuery sortable feature where I have two lists and can move items between them: $( '#productsList, #orderList' ) .sortable({connectWith: '.containerDiv'}) .disableSelection(); My issue arises when I try to implement ...