-1

Sort my json in format as below :

 [{"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 I have json as below :

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

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 hint please will really help me out.

6

3 Answers 3

0

You could take an array for the months, sort the given data by year and month and use an index for the data array for maping a whole year until all years are mapped.

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; }

2
  • what are you working so hard for? That's just too much complication for a relatively simple task.
    – DEVCNN
    CommentedAug 6, 2018 at 7:53
  • thanx @NinaScholz
    – Raj Dubey
    CommentedAug 6, 2018 at 8:51
0
function sortElements(arr){ arr.sort((a, b) => new Date(a.x).getTime() - new Date(b.x).getTime() ); } 
1
  • 1
    Although this code might (or might not) solve the problem, a good answer should also contain an explanation on how the code works.
    – BDL
    CommentedAug 6, 2018 at 8:17
0

You can take help of moment.js to get all months and than traverse through it and create output array from it.

 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>

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.