Organize, filter, and compare an array of objects using a specific format

Organize my JSON data in the following format:

    [{"x":"Jan-2017","y":41},{"x":"Feb-2017","y":20},{"x":"Mar-2017","y":45},{"x":"Apr-2017","y":29},{"x":"May-2017","y":59},{"x":"Jun-2017","y":378},{"x":"Jul-2017","y":354},{"x":"Aug-2017","y":398},{"x":"Sep-2017","y":390},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]

For example:

If the JSON data is as follows:

    [{"x":"Aug-2017","y":398},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]

The expected result should be:

    [{"x":"Jan-2017","y":0},{"x":"Feb-2017","y":0},{"x":"Mar-2017","y":0},{"x":"Apr-2017","y":0},{"x":"May-2017","y":0},{"x":"Jun-2017","y":0},{"x":"Jul-2017","y":0},{"x":"Aug-2017","y":398},{"x":"Sep-2017","y":0},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]

Any help or suggestions would be greatly appreciated.

Answer №1

To organize the given data by year and month, you can create an array for the months, sort the data, and then map the entire year using a data array index.

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    data = [{ x: "Aug-2017", y: 398 }, { x: "Oct-2017", y: 579 }, { x: "Nov-2017", y: 651 }, { x: "Dec-2017", y: 832 }]
        .sort(({ x: a }, { x: b }) => {
            var aa = a.split('-'),
                bb = b.split('-');
            return aa[1] - bb[1] || months.indexOf(aa[0]) - months.indexOf(bb[0]);
        }),
    index = 0,
    year = data[0].x.slice(-4),
    result = [];

do {
    result.push(...months.map(month =>
        data[index] && data[index].x.slice(0, 3) === month
            ? data[index++]
            : { x: [month, year].join('-'), y: 0 }
    ));
} while (year++ < data[data.length - 1].x.slice(-4))

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

function arrangeItems(array){
array.sort((item1, item2) => 
  new Date(item1.time).getTime() - new Date(item2.time).getTime()
);
}

Answer №3

If you're looking to generate an array of all months using moment.js, here's a simple solution for you. Just iterate through the months and create an output array based on your requirements.

 var input = [{"x":"Aug-2017","y":398},{"x":"Oct-2017","y":579},{"x":"Nov-2017","y":651},{"x":"Dec-2017","y":832}]
var allmonths = moment.monthsShort();
var year = 2017;
var output = allmonths.map((el,i) => {
let temp;
 return input.some((a) =>  a.x == el+"-"+year ? temp = a:false) ? temp:{x:el+"-"+year,y:0};
});
 
console.log(output); 
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

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

dojo.xhrGet evaluating script tags

I have a piece of code that is similar to the following: var targetElem = dojo.byId('xyz'); var xhrArgs = { url: 'Welcome.do?call=JS', preventCache: true, load: function(data){ targetElem.innerHTML = data; dojo.parser.par ...

Step-by-step Guide on Initializing Materialize Dropdown Button in React

I'm currently working on this code where I need the dropdown button to function properly. Although the button appears, it doesn't work when clicked. import React, {useContext} from 'react'; import {Link, useNavigate} from 'react-ro ...

Searching for items in an array of objects using Vue.js

Here is an example of a Laravel API response: { id:1, name: "Text", category: { id: 1, name: "Text 2", }, tags:[ { id: 1, name: "Tag1", }, { id: 2, name: "Tag2", ...

Using Angular directives to pre-select a default option

I am currently working on a select HTML tag with two options, and I want to set the first option as the default choice. My select element includes Angular directives like ng-change and ng-model. I have attempted to achieve this by adding selected = "select ...

Creating a textured path using Threejs

Having trouble drawing a path in my 3D world, as the line class is not helpful. Can anyone offer assistance? See this image I've updated my question I want to draw a path and fill it with texture. var SUBDIVISIONS = 20; geometry = new THREE.Geo ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

Unrecognized provider injected into AngularJS Project

I've encountered an error when running my Angular app despite installing all necessary packages using npm. Could this issue be stemming from a version conflict between Angular and angular-animate? Uncaught Error: [$injector:unpr] Unknown provider: $$ ...

Choosing Between AngularJS and Laravel - Which One is Right for You?

Currently, I am working on developing a web, iOS, and Android app at the same time. I have configured Phalcon to connect with Cassandra database, utilizing it as an API gateway. All requests are made through HTTP and go through the Phalcon application bef ...

Node.js routing at the secondary level modifies the main directory path

In my current web project, I am incorporating both Angular JS and Node JS simultaneously. To handle routing in Angular JS, I have implemented the following code: app.config(function($routeProvider,$locationProvider) { $routeProvider .when("/expert/:exper ...

Invoking the HTML method from a WCF service

Currently, I am utilizing a callback in my WCF service to receive raw frames from the camera. I am currently working on developing an HTML application that will showcase these frames. However, my current approach involves using a button click event in HTM ...

Attachment Image in Nodemailer Is Missing Data

I am encountering an issue with sending an image attachment where it is coming through with no data, showing a size of 0kb. Below is the code I am using: var path = require('path'); var uploadDir = path.dirname(require.main.filename); var img ...

Tips for dynamically loading images in React with a Collage component

It appears that all the examples I've come across are static in terms of loading images. While the code works, it does not display the divider <div> tag as expected. Instead, the results (images) are shown stacked in the first item of the Collag ...

Encountering a ng-select2 Error with Angular version 4.1.3

I have recently installed the ng-select2 package, but I encountered an error when trying to compile my code using 'ng serve'. Node version: 8.10.0 NPM version: 6.0.0 Another list item Operating System: Windows 7 ERROR in d:/PATH-TO-PROJECT-F ...

dynamically open ngx-bootstrap accordion panels

I implemented the ngx-bootstrap accordion feature to display a list of blog posts. Below is the template structure: <accordion id="blog-list"> <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.i ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

Dynamically adding items in a row to a form panel using extjs

While using ExtJS 3.4, I faced a challenge with laying out three buttons in a row within a formpanel. After some research, I discovered that nesting item blocks might be the correct approach. Below is the code snippet showcasing what I have implemented: v ...

Encountering a Template Parse Error after running the ng build --prod command

As a newcomer to Angular, I have successfully created a small application that requires a sortable table. Everything works well in Angular-cli development server during development mode (using ng serve). I've experimented with implementing the table ...

Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method, [HttpGet] public ActionResult GetStudents() { Student std1 = new Student(); List<Student> stdlst = new List<Student>(); std1.Id = 1; ...

Can you explain the purpose and function of angular routing resolve?

As I delved into the contents of this article Authentication Article, I found myself puzzled by a particular section: resolve: { loggedin: checkLoggedin } I couldn't help but wonder whether loggedin is a fixed term or if it can be customized based o ...

Currently, I am utilizing a Google script to import my emails into a spreadsheet. I am seeking help in identifying and fixing a duplication issue that

For the past few weeks, I have been running a script to gather task data for my company. The script has been running smoothly since 09/03/2023, but recently it started duplicating entries and causing confusion in identifying which tasks are necessary and w ...