JavaScript: organizing data by category with summarization

I have a basic JSON list provided below:

{
"myList": [
    {

        "endOfPeriod": 1461362400000,
        "rate": 0.03726378
    },
    {
        "endOfPeriod": 1461535200000,
        "rate": 0.03726378
    },
    {
        "endOfPeriod": 1461967200000,
        "rate": 0.03708314
    },
    {
        "endOfPeriod": 1461708000000,
        "rate": 0.03492851
    },
    {
        "endOfPeriod": 1461794400000,
        "rate": 0.03845068
    },
    {
        "endOfPeriod": 1461621600000,
        "rate": 0.03544827
    }
]

}

In this example, the endOfPeriod value is represented as a Unix epoch timestamp. Although all the timestamps in the sample data correspond to April 2016, they could belong to other time periods as well. Assuming that I have already converted this JSON list into an array and transformed each Unix timestamp into a DD.MM.YYYY date format (or kept them as Unix timestamps), I need to find an effective method to create a new array containing the most recent rate for each month/year group.

The task requires writing JavaScript code.

For instance:

20.04.2016 / 0.33
21.04.2016 / 0.55
14.04.2016 / 0.88
02.05.2016 / 1.33
01.05.2016 / 5.44

The resulting array should include:

21.04.2016 / 0.55
02.05.2016 / 1.33

Thank you for your assistance.

Answer №1

If my understanding is correct, you are looking to retrieve the latest rate for each month. My recommendation would be to utilize lodash.

_.chain(data)
  .groupBy(function(entry) {
    var date = new Date(entry.endOfPeriod);
    return date.getFullYear() + '-' + date.getMonth();
  })
  .map(function(group) {
    return _.maxBy(group, function(entry) {
      return entry.endOfPeriod;
    });
  })
  .value()

We begin with a collection of objects structured like this:

{
    "endOfPeriod" : 1464818400000,
    "rate" : 0.05
}

The chain() method encloses the data within a lodash object.

Subsequently, we group the elements by year and month. Following the groupBy() operation, the structure will resemble:

{
  "2016-3" : [array of entries in April 2016],
  "2016-4" : [array of entries in May 2016]
  ...
}

For each group, we identify the item with the highest endOfPeriod.

Lastly, value() reverses the process to transform the lodash object back into a regular Javascript array.

Answer №2

While I could provide a solution here without relying on lodash, I believe it's best to avoid reinventing the wheel.

const myList = [
  {
    "endOfPeriod": 1461362400000,
    "rate": 0.03726378
  },
  {
    "endOfPeriod": 1461535200000,
    "rate": 0.03726378
  },
  {
    "endOfPeriod": 1461967200000,
    "rate": 0.03708314
  },
  {
    "endOfPeriod": 1461708000000,
    "rate": 0.03492851
  },
  {
    "endOfPeriod": 1461794400000,
    "rate": 0.03845068
  },
  {
    "endOfPeriod": 1461621600000,
    "rate": 0.03544827
  }
];

const res = myList.reduce((prev, current) => {
  const date = new Date(current.endOfPeriod);
  const month = date.getMonth();
  const year = date.getFullYear();

  const key = `${year}-${month}`;

  if (prev[key] && prev[key].endOfPeriod < current.endOfPeriod) {
    prev[key] = current;
  } else {
    prev[key] = current;
  }

    return prev;
}, {});


const finalResult = Object.keys(res).map((key) => {
  return {
    key: res[key].rate
  }
});

console.log(finalResult);

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

Unable to assign an attribute to an HTML element without a value ('hidden')

In my quest to dynamically toggle the hidden attribute on certain HTML elements, I have come up with the following code snippet: <li><a href="#" onclick="SelectImage( 5 ); return false;">6</a></li> ... <a href="/image/5">< ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Attempting to verify the HTML output, yet it remains unspecified

After developing a basic testing framework, I have set myself the challenge of creating a single-page web application using vanilla JavaScript. I've been facing difficulties in figuring out why my view test is not recognizing the 'list' con ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Steps for developing the server side in PHP when utilizing JSON on the client side of an iPhone

Is it possible to use JSON directly to parse server-side code written in PHP? If so, could you provide some examples of how this can be done when wanting to integrate JSON on the client side? I am interested in making my server side in PHP and incorporati ...

Is the new mui LoadingButton not available in the latest version?

According to the material UI documentation found at here, you are supposed to import LoadingButton from '@material-ui/lab/LoadingButton'; However, I am unable to locate this folder within mui/lab and the import statement is resulting in an erro ...

Implementing a list using display: inline-block without any specified order

Currently, I am immersed in a project that involves simulating an input using HTML and CSS. This input should be capable of executing a function like: my_cool_function(param0, param1, param2, param3). To accomplish this, I have constructed an unordered lis ...

Running multiple controller functions in nodejs can be achieved by chaining them together in the desired

Currently, I am working on the boilerplate code of mean.io and adding a password reset email feature to it. Whenever a user requests a password reset with their email as a parameter, I generate a unique salt (resetid) and send them an email with a link con ...

JavaScript Logic to Check if an Element is Hidden

I'm having trouble figuring out how to close an element when another element collapses. I've searched for solutions without success. My structure is updated using Bootstrap and JavaScript, but it doesn't function as expected. Specifically, ...

The issue with getting a token from Next-auth on the server side persists

Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side. I have double-checked my callbacks configuration ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Accessing id3 v2.4 tags using the built-in capabilities of Chrome's Javascript FileReader and DataView

After discovering the solution provided by ebidel, individuals can extract id3v1 tags using jDataView: document.querySelector('input[type="file"]').onchange = function (e) { var reader = new FileReader(); reader.onload = function (e) { ...

Executing a function with the initial click

Is there a way to run a function only on the first click, without having it run every time? I already have another function running on window.onload, so I can't use that. Both functions work fine independently, but not together. Right now, I'm ca ...

What is the best method for sending a document to a web API using Ajax, without relying on HTML user controls or forms?

I have successfully utilized the FormData api to upload documents asynchronously to a web api whenever there is a UI present for file uploading. However, I now face a situation where I need to upload a document based on a file path without relying on user ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...

What could be causing the Twitter Timeline to fail to load based on a variable in a Vue.js component?

My goal is to display the Twitter timeline of multiple accounts based on the route. I initially attempted to use a plugin called vue-tweet-embed, but encountered issues with it. As a result, I resorted to the traditional method by embedding twitter's ...

An unforeseen SyntaxError has occurred: Unexpected token : found in the JSON data returned from an AngularJS API request

Currently, I'm encountering an error that leads me to a JSON response when clicking on the provided link: {"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop",.....} My issue arises while making a get reques ...

Using JQuery to create an animated slideToggle effect for a multicolumn list

I have a large list where each li element has a width of 33%, resulting in 3 columns: computers monitors hi-fi sex-toys pancakes scissors Each column contains a hidden UL, which is revealed through slideToggle on click. JQuery $('.subCate ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...