Getting Missing Months - javascript

I am working on a project where I am trying to chart the number of monthly order that I have received. My current data for monthlyOrder is:
[
{
_id: { month: 12, year: 2021 },
year: 2021,
month: 'December',
orders: 1
},
{
_id: { month: 4, year: 2022 },
year: 2022,
month: 'April',
orders: 31
},
{
_id: { month: 5, year: 2022 },
year: 2022,
month: 'May',
orders: 2
}
]
I would like to have an array with all missing months with orders: 0, so that all months since the first month/date are included in the chart.
I have attempted to do this by:
let startYear = monthlyOrders[0]._id.year;
let startMonth = monthlyOrders[0]._id.month;
let endYear = monthlyOrders[monthlyOrders.length - 1]._id.year;
let endMonth = monthlyOrders[monthlyOrders.length - 1]._id.month;
let months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
function getMonthlys () {
if (startYear === endYear) {
if (startMonth === endMonth) {
let date = {
month: startMonth,
year: startYear,
}
if (startMonth < endMonth) {
let months = 1;
while (months <= endMonth) {
months = months + 1;
}
let date =
{
month: months,
year: startYear,
}
}
}
}
}
However, this is probably not the best way to do this, and I am not sure how to deal with dates where startYear < endYear, but startMonth === endMonth.
Additionally, to deal with adding 0 for orders when one doesn't exist I have tried to do this:
let monthsObj = [];
for (let i = startYear; i <= endYear; i++) {
for (let j = startMonth; j <= 12; j++) {
if (!(j > endMonth && i === endYear)) {
let obj = {
month: j,
year: i,
};
monthsObj.push(obj);
}
}
}
for (let dateVal of monthsObj) {
let isInArray = false;
for (let dayVal of monthlyOrders) {
if (dayVal._id.year == dateVal.year && dayVal._id.month == dateVal.month) {
isInArray = true;
}
}
if (isInArray === false) {
let obj = {
month: dateVal.month,
year: dateVal.year,
};
monthlyOrders.push({ _id: obj, year: dateVal.year, month: months[dateVal.month - 1], orders: 0 });
}
}
I would really appreciate any suggestion or on how to get the:
[
{
_id: { month: 12, year: 2021 },
year: 2021,
month: 'December',
orders: 1
},
{
_id: { month: 1, year: 2022 },
year: 2022,
month: 'January',
orders: 0
},
{
_id: { month: 2, year: 2022 },
year: 2022,
month: 'February',
orders: 0
},
{
_id: { month: 3, year: 2022 },
year: 2022,
month: 'March',
orders: 0
},
{
_id: { month: 4, year: 2022 },
year: 2022,
month: 'April',
orders: 31
},
{
_id: { month: 5, year: 2022 },
year: 2022,
month: 'May',
orders: 2
}
]
array that I need.

However, this is probably not the best way to do this, and I am not sure how to deal with dates where startYear < endYear, but startMonth === endMonth.
I think an easier approach would be for each iteration of the loop to add a single object to the output array, along with keeping track of the current index of the input array being iterated over. If, on an iteration, the object in the input array has a matching month and year, push it - otherwise, push the placeholder object (with the one-indexed month accounted for). Then, if index being iterated over is the final one in the original array, break - otherwise, increment the month and then (if needed) the year.
const monthlyOrders=[{_id:{month:12,year:2021},year:2021,month:"December",orders:1},{_id:{month:4,year:2022},year:2022,month:"April",orders:31},{_id:{month:5,year:2022},year:2022,month:"May",orders:2}];
const months=["January","February","March","April","May","June","July","August","September","October","November","December"];
let { year, month } = monthlyOrders[0]._id;
const endYear = monthlyOrders[monthlyOrders.length - 1]._id.year;
const endMonth = monthlyOrders[monthlyOrders.length - 1]._id.month;
const output = [];
let monthlyOrdersIndex = 0;
while (monthlyOrdersIndex !== monthlyOrders.length) {
// If the month/year we're on exists in the original array, use it:
if (year === monthlyOrders[monthlyOrdersIndex]._id.year && month === monthlyOrders[monthlyOrdersIndex]._id.month) {
output.push(monthlyOrders[monthlyOrdersIndex]);
monthlyOrdersIndex++;
} else {
output.push({
_id: { month, year },
year: year,
month: months[month - 1],
orders: 0
});
}
month = month === 12 ? 1 : month + 1;
if (month === 1) year++;
}
console.log(output);

You can use the javascript Date object to compare an step through the months. Your code, I couldn't tell what it was doing with each month, but this adds them to an array and returns it.
let startYear = 2021;
let startMonth = 6;
let endYear = 2023;
let endMonth = 2;
let months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
function getMonthlys () {
var list = []
var startdate = new Date(startYear, startMonth, 1)
var enddate = new Date(endYear, endMonth, 1)
while (startdate < enddate) {
list.push({
month: startdate.getMonth(),
year: startdate.getFullYear()
})
startdate.setMonth(startdate.getMonth() + 1)
}
return list
}
var allmonths = getMonthlys();
Then you just need to find the data for each one of those months
// for each month, find a match
var orders = allmonths.map( function(month) {
var match = datasrc.find(function(entry) {
return entry._id.month == month.month && entry._id.year == month.year
});
if (match) {
return match
}
else {
return {
_id: month,
month: months[month.month-1],
year: month.year,
orders: 0
}
}
})
You can see in this fiddle
https://jsfiddle.net/myt19j30/1/

Related

Convert two arrays to one object, with same key for each array in Javascript

For example, I have two arrays like these.
const dateArray = ['January', 'February', 'March', 'April', 'May', 'June']
const InfoArray = [
{ Date : '2022-01', Active: 1 },
{ Date : '2022-02', Active: 12 },
{ Date : '2022-03', Active: 25 },
{ Date : '2022-04', Active: 33 },
{ Date : '2022-05', Active: 120 },
{ Date : '2022-06', Active: 335 },
]
However, I want combined these two arrays into an array of objects.
const result = [
{ month: 'January', Active: 1 },
{ month: 'February', Active: 12 },
{ month: 'March', Active: 25 },
{ month: 'April', Active: 33 },
{ month: 'May', Active: 120 },
{ month: 'June', Active: 335 },
]
I looked for some information, and did like
const makeObjectWithTwoArray = () => {
let chartObj = {}
dateArray.forEach((element, index) => {
chartObj[element] = infoArray[index]
})
return chartObj
}
however doesn't work at all. (of course because each array can't have same keys with the code.)
Your help will be much appreciated.
You can use the function Array.prototype.map as follows:
const dateArray = ['January', 'February', 'March', 'April', 'May', 'June']
const InfoArray = [
{ Date : '2022-01', Active: 1 },
{ Date : '2022-02', Active: 12 },
{ Date : '2022-03', Active: 25 },
{ Date : '2022-04', Active: 33 },
{ Date : '2022-05', Active: 120 },
{ Date : '2022-06', Active: 335 },
];
const result = InfoArray.map(({Date, Active}) => {
const [_, month] = Date.split("-");
return {Active, month: dateArray[[Number(month) - 1]]};
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const dateArray = ['January', 'February', 'March', 'April', 'May', 'June']
const InfoArray = [
{ Date : '2022-01', Active: 1 },
{ Date : '2022-02', Active: 12 },
{ Date : '2022-03', Active: 25 },
{ Date : '2022-04', Active: 33 },
{ Date : '2022-05', Active: 120 },
{ Date : '2022-06', Active: 335 },
]
const result = InfoArray.map(item => {
const monthNumber = item.Date.split('-')[1]
const month = dateArray[+monthNumber - 1]
return {
Active: item.Active,
month
}
})
console.log(result)
You Actually don't need the dateArray you can just extract the month name from the Date property.
const InfoArray = [
{ Date : '2022-01', Active: 1 },
{ Date : '2022-02', Active: 12 },
{ Date : '2022-03', Active: 25 },
{ Date : '2022-04', Active: 33 },
{ Date : '2022-05', Active: 120 },
{ Date : '2022-06', Active: 335 },
]
let result = InfoArray.map(e => ({
month: new Date(e.Date).toLocaleString('default', {month: 'long'}),
Active: e.Active
}))
console.log(result)
Another alternative is using .reduce.
Note: I didn't return [...arr, {...}] implicitly since it would have created a different array on each iteration. return arr is better if you are going to have a large data (potenitally)
const dateArray = ['January', 'February', 'March', 'April', 'May', 'June']
const InfoArray = [
{ Date : '2022-01', Active: 1 },
{ Date : '2022-02', Active: 12 },
{ Date : '2022-03', Active: 25 },
{ Date : '2022-04', Active: 33 },
{ Date : '2022-05', Active: 120 },
{ Date : '2022-06', Active: 335 },
]
const combined = InfoArray.reduce((arr, {Date, Active}) => {
arr.push({
Date: dateArray[Number(Date.split("-")[1]) -1],
Active
})
return arr
}, [])
console.log("combined: ", combined)

Find missing months in js array

I have the following Array
[
{ Month: '2021-05', Count: 36 },
{ Month: '2021-06', Count: 1048 },
{ Month: '2021-07', Count: 572 },
{ Month: '2021-09', Count: 3 },
{ Month: '2021-12', Count: 52 },
{ Month: '2022-01', Count: 4 },
{ Month: '2022-02', Count: 273 },
{ Month: '2022-04', Count: 96 }
]
where I am missing a few months. I know how many months is needed (could be 12 or could be more or less) and I need the missing months (like 2021-08 in this case) to be added with a count of 0. How to go about it?
Here's a pure, functional approach which will create a new array with new items, inserting all of the missing months in order. The code includes some comments explaining the procedure:
const parseDate = str => str.split('-').map(Number);
const formatDate = (year, month) => `${year}-${String(month).padStart(2, '0')}`;
function createContinuousMonthCounts (array) {
const all = [];
// get initial year/month values from first item
let [year, month] = parseDate(array[0].Month);
const advanceDate = () => {
month += 1;
if (month > 12) {
year += 1;
month = 1;
}
};
for (const item of array) {
const [y, m] = parseDate(item.Month);
// while the current month is not equal to the current item's month,
// create an entry for the month, append it, and advance to the next month
while (year !== y || month !== m) {
all.push({Month: formatDate(year, month), Count: 0});
advanceDate();
}
// after we're up to date, add the current item and advance the date
all.push({...item});
advanceDate();
}
return all;
}
const array = [
{ Month: '2021-05', Count: 36 },
{ Month: '2021-06', Count: 1048 },
{ Month: '2021-07', Count: 572 },
{ Month: '2021-09', Count: 3 },
{ Month: '2021-12', Count: 52 },
{ Month: '2022-01', Count: 4 },
{ Month: '2022-02', Count: 273 },
{ Month: '2022-04', Count: 96 },
];
const all = createContinuousMonthCounts(array);
for (const {Month, Count} of all) console.log(Month, Count);
Just a shot into the dark (please consider adding some Code to your question):
const months = [
{ Month: '2021-05', Count: 36 },
{ Month: '2021-06', Count: 1048 },
{ Month: '2021-07', Count: 572 },
{ Month: '2021-09', Count: 3 },
{ Month: '2021-12', Count: 52 },
{ Month: '2022-01', Count: 4 },
{ Month: '2022-02', Count: 273 },
{ Month: '2022-04', Count: 96 }
];
const neededMonths = [
"2021-01","2021-02","2021-03","2021-04","2021-05","2021-06","2021-07","2021-08","2021-09","2021-10","2021-11","2021-12"
]
const missedMonths = [];
months.map( m => {
if(neededMonths.indexOf(m.Month) == -1 ){
missedMonths.push(m.Month);
}
});
console.log(missedMonths);
You first need a method to find all the months between a range, then iterate across all the months and add the missing ones with count: 0:
const months = [
{ Month: '2021-05', Count: 36 },
{ Month: '2021-06', Count: 1048 },
{ Month: '2021-07', Count: 572 },
{ Month: '2021-09', Count: 3 },
{ Month: '2021-12', Count: 52 },
{ Month: '2022-01', Count: 4 },
{ Month: '2022-02', Count: 273 },
{ Month: '2022-04', Count: 96 }
]
const firstMonth = months.at(0).Month;
const lastMonth = months.at(-1).Month;
const [initialYear, initialMonth] = firstMonth.split('-');
const [endingYear, endingMonth] = lastMonth.split('-');
const allMonths = [];
let currentMonth = initialMonth;
let currentYear = initialYear;
while (`${currentYear}-${(''+currentMonth).padStart(2, '0')}` !== lastMonth) {
allMonths.push(`${currentYear}-${(''+currentMonth).padStart(2, '0')}`);
currentMonth++;
if (currentMonth === 13) {
currentMonth = 1;
currentYear++;
}
}
allMonths.forEach(month => {
if (!months.find(m => m.Month === month)) {
months.push({Month: month, count: 0});
}
});
console.log(months);

Create 2 Dimensional Array from Object with same key

I have an array of objects that I want to transform. My dataset looks like this:
[
{
day: sunday,
val: 20
},
{
day: sunday,
val: 20
},
{
day: monday,
val: 10
},
{
day: monday,
val: 30
},
{
day: tuesday,
val: 5
},
{
day: tuesday,
val: 5
}
]
I am trying to transform the data to look like this:
Output:
[[20,20], [10,30], [5, 5]]
Where each of the nested arrays are based on the Day of Week in object. Any ideas?
Thanks!
You could group your items by their day. After you have the groups, you can grab the values of the map and map the item lists to a list of val.
const data = [
{ day: 'sunday' , val: 20 }, { day: 'sunday' , val: 20 },
{ day: 'monday' , val: 10 }, { day: 'monday' , val: 30 },
{ day: 'tuesday' , val: 5 }, { day: 'tuesday' , val: 5 }
];
const transformed = Object.values(data.reduce((map, item) =>
({ ...map, [item.day] : [ ...(map[item.day] || []), item]
}), {})).map(list => list.map(item => item.val));
console.log(transformed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Alternatively, you can reduce the values right away, but you lose all the item properties.
const data = [
{ day: 'sunday' , val: 20 }, { day: 'sunday' , val: 20 },
{ day: 'monday' , val: 10 }, { day: 'monday' , val: 30 },
{ day: 'tuesday' , val: 5 }, { day: 'tuesday' , val: 5 }
];
const transformed = Object.values(data.reduce((map, item) =>
({ ...map, [item.day] : [ ...(map[item.day] || []), item.val] }), {}));
console.log(transformed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Here is a functional version:
const data = [
{ day: 'sunday' , val: 20 }, { day: 'sunday' , val: 20 },
{ day: 'monday' , val: 10 }, { day: 'monday' , val: 30 },
{ day: 'tuesday' , val: 5 }, { day: 'tuesday' , val: 5 }
];
const toMatrix = (list, key, valFn) => Object.values(data.reduce((map, item) =>
({ ...map, [item[key]] : [ ...(map[item[key]] || []), valFn(item) ] }), {}))
console.log(toMatrix(data, 'day', item => item.val));
.as-console-wrapper { top: 0; max-height: 100% !important; }
let myarray=[
{
day: 'sunday',
val: 20
},
{
day: 'sunday',
val: 20
},
{
day: 'monday',
val: 10
},
{
day: 'monday',
val: 30
},
{
day: 'tuesday',
val: 5
},
{
day: 'tuesday',
val: 5
}
];
let newarray=[];
for (let x of myarray) {
if (!newarray[x.day]) { newarray[x.day]=[]; }
newarray[x.day].push(x.val);
}
console.log(newarray);
This could be a solution:
var obj = [
{
day: 'sunday',
val: 20
},
{
day: 'sunday',
val: 20
},
{
day: 'monday',
val: 10
},
{
day: 'monday',
val: 30
},
{
day: 'tuesday',
val: 5
},
{
day: 'tuesday',
val: 5
}
]
var obj_output = [];
var bln_array = false;
for (i=0; i < obj.length; i++) {
var arr = [];
arr.push(obj[i].val);
arr.push(obj[i+1].val);
obj_output.push(arr);
i = i+1
}
console.log(obj_output);
Here's one way to achieve this
var old = [
{ day: 'sunday', val: 20 },
{ day: 'sunday', val: 20 },
{ day: 'monday', val: 10 },
{ day: 'monday', val: 30 },
{ day: 'tuesday', val: 5 },
{ day: 'tuesday', val: 5 }
];
var days = [];
var result = [];
old.forEach(o => {
if(days.indexOf(o.day) === -1) {
days.push(o.day);
result.push([]);
}
result[days.indexOf(o.day)].push(o.val);
});
console.log(result);
Here is an example on stackblitz on how you could achieve that, and here is the code :
import React, { Component } from "react";
import { render } from "react-dom";
import * as _ from "lodash";
const App = () => {
const data = [
{
day: "sunday",
val: 20
},
{
day: "sunday",
val: 20
},
{
day: "monday",
val: 10
},
{
day: "monday",
val: 30
},
{
day: "tuesday",
val: 5
},
{
day: "tuesday",
val: 5
}
];
const groupBy = (arr, prop) => {
const map = new Map(Array.from(arr, obj => [obj[prop], []]));
arr.forEach(obj => map.get(obj[prop]).push(obj.val));
return Array.from(map.values());
};
React.useEffect(() => {
// groupBy from Lodash does not do exaclty what you want (but still very interesting), need to work on it a bit
let chunks = Object.values(_.groupBy(data, 'day')).map(x => x.map(item => item.val));
console.log(chunks);
// Exactly what you want, but custom made by someone here :
// https://stackoverflow.com/a/53704154/9868549
console.log(groupBy(data, 'day'));
}, []);
return <div>This is a template react</div>;
};
render(<App />, document.getElementById("root"));
I found it here on another StackOverflow thread but still wanted to provide another solution with lodash.

Nodejs - Express - How to calculate the next closer time to today()?

I need to calculate which is the next closer hour to "time" taking into account the following array data:
var date = new Date();
var time = date.getHours(); // 17 -> it means 5:00 PM
var minute = date.getMinutes(); // 12
// This is how the data has been saved in the database.
{ id: ‘1’, time: '1:00 AM' }
{ id: ‘1’, time: '2:00 PM' }
{ id: ‘1’, time: '7:00 PM' }
{ id: ‘1’, time: '10:00 PM' }
{ id: ‘1’, time: '8:00 PM' }
{ id: ‘1’, time: '11:00 AM' }
{ id: ‘2’, time: '9:00 AM' }
{ id: ‘2’, time: '6:30 PM' }
{ id: ‘2’, time: '5:00 PM' }
{ id: ‘2’, time: '1:00 PM' }
The result need to be an array like this:
{id: ‘1’, time: '7:00 PM'}
{id: ‘2’, time: '6:30 PM'}
Basically I need to know which is the next closer time to 5:12 PM for each ID.
This is my code so far:
function calculateNextPill(items) {
let nextPillArr = [];
let itemData = null;
let item_id = null;
var currentTime = new Date();
var closerTime = new Date();
var newTimes = [];
for(i=0; i<items.length; i++) {
itemData = items[i].itemdata[0];
item_id = items[i]._id;
for (const prop in itemData.pills) {
const pill = itemData.pills[prop];
if (pill != undefined && pill.time != undefined) {
nextPillArr.push({id: item_id, time: pill.time});
}
}
}
nextPillArr.forEach(element => {
var time = element.time;
var scheduleTime = new Date();
var parts = time.match(/(\d+):(\d+) (AM|PM)/);
if (parts) {
var hours = parseInt(parts[1]),
minutes = parseInt(parts[2]),
tt = parts[3];
if (tt === 'PM' && hours < 12) hours += 12;
scheduleTime.setHours(hours, minutes, 0, 0);
var a = moment(currentTime);
var b = moment(scheduleTime);
b.diff(a);
newTimes.push({id: element._id, diff: b.diff(a)});
// here I need to calculate which time is closer for which pill. Not done yet. Need more coffe...
}
});
}
First you need a function that lets you get some kind of numeric value for each time that you can then use to compare the values. The following function will give us the amount of minutes in 24h format:
function time_to_numeric(time) {
const [_, h, m, meridian] = time.match(/(\d+):(\d+) (AM|PM)/);
let [hours, min] = [parseInt(h), parseInt(m)];
if (meridian === "PM" && hours !== 12) hours += 12;
if (meridian === "AM" && hours === 12) hours -= 12;
return hours * 60 + min;
}
Next, we also need the time in the same format for now:
const now = new Date();
const now_numeric = now.getHours() * 60 + now.getMinutes();
Using this, we can now start finding the closest times for each unique id assuming items is an array of all the objects in your example. This works by computing the difference in minutes to now and swapping the value if it lower. In the case of a time occuring earlier than now, we instead compute the difference to that time the next day. We save both the difference and the actual time for the current minimum for each id:
const closer_times_by_id = items.reduce((acc, {id, time}) => {
const time_numeric = time_to_numeric(time);
let diff = time_numeric - now_numeric;
if (diff < 0) diff = time_numeric + MINUTES_PER_DAY - now_numeric;
const prev_diff = acc[id] && acc[id].diff;
if (prev_diff === undefined || diff < prev_diff) {
acc[id] = { diff, time };
}
return acc;
}, {});
Now our closer_times_by_id will look something like {'1': {diff: 158, time: '7:00 PM'}, '2': {diff: 38, time: '5:00 PM'}}. We map this to an array in the following way:
times_arr = Object.entries(closer_times_by_id).map(item => {
const [id, { time }] = item;
return { id, time };
});
After this, we are done and times_arr contains your result.
Full code:
const MINUTES_PER_DAY = 24 * 60;
// Takes a string like '1:10 PM' and returns the amount of minutes in 24h format
function time_to_numeric(time) {
const [_, h, m, meridian] = time.match(/(\d+):(\d+) (AM|PM)/);
let [hours, min] = [parseInt(h), parseInt(m)];
if (meridian === "PM" && hours !== 12) hours += 12;
if (meridian === "AM" && hours === 12) hours -= 12;
return hours * 60 + min;
}
function closest_items_by_id(items) {
const now = new Date();
const now_numeric = now.getHours() * 60 + now.getMinutes();
// Find closest times for each id, giving preference to times in the
// future in case of ties
// After reducing has finished, closer_times_by_id will be an object like
// {'1': {diff: 158, time: '7:00 PM'}, '2': {diff: 38, time: '5:00 PM'}}
const closer_times_by_id = items.reduce((acc, {id, time}) => {
const time_numeric = time_to_numeric(time);
let diff = time_numeric - now_numeric;
// If time occured earlier than now, calculate diff to time next day
if (diff < 0) diff = time_numeric + MINUTES_PER_DAY - now_numeric;
const prev_diff = acc[id] && acc[id].diff;
if (prev_diff === undefined || diff < prev_diff) {
acc[id] = { diff, time };
}
return acc;
}, {});
// Map closer_times_by_id to desired format
return Object.entries(closer_times_by_id).map(item => {
const [id, { time }] = item;
return { id, time };
});
}
const raw_data = [
{ id: '1', time: '1:00 AM' },
{ id: '1', time: '11:00 AM' },
{ id: '1', time: '2:00 PM' },
{ id: '1', time: '7:00 PM' },
{ id: '1', time: '8:00 PM' },
{ id: '1', time: '10:00 PM' },
{ id: '2', time: '9:00 AM' },
{ id: '2', time: '1:00 PM' },
{ id: '2', time: '1:10 PM' },
{ id: '2', time: '5:00 PM' },
{ id: '2', time: '6:30 PM' },
]
const now = new Date();
console.log(`Time at SO-server: ${now.getHours()}:${now.getMinutes()}`);
console.log(closest_items_by_id(raw_data));

How to sort the object based on array - javascript?

I have months values like below
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var objects = {
April:0,
August:4182,
December:0,
February:0,
January:1,
July:2,
June:0,
March:0,
May:0,
November:0,
October:0,
September:1518
}
How to sort the objects based on the months array?
Try with:
var output = [];
for (var k in months) {
var month = months[k];
output.push({name: month, value: objects[month]});
}
It will returns you ordered list of objects that contain name and value keys which have proper month name and its value.
var values = [];
for(var i = 0; i < months.length; i++) {
vals.push(objects[months[i]]);
}
This way you get the object properties' values ordered by the months array.
You can't sort the properties in an object, because the order of the properties is not maintained. If create an object like that, then loop out the properties, you will see that the properties may not be returned in the same order that you put them in the object, and different browsers will return the properties in differend order.
Make the object an array, so that it can maintain the order of the values, and make the lookup array an object so that you can efficiently map a string to a numeric value:
var months = {
January: 1,
February: 2,
March: 3,
April: 4,
May: 5,
June: 6,
July: 7,
August: 8,
September: 9,
October: 10,
November: 11,
December: 12
};
var objects = [
{ name: 'April', value: 0 },
{ name: 'August', value: 4182 },
{ name: 'December', value: 0 },
{ name: 'February', value: 0 },
{ name: 'January', value: 1 },
{ name: 'July', value: 2 },
{ name: 'June', value: 0 },
{ name: 'March', value: 0 },
{ name: 'May', value: 0 },
{ name: 'November', value: 0 },
{ name: 'October', value: 0 },
{ name: 'September', value: 1518 }
];
Now you can sort the array using the object:
objects.sort(function(x,y) { return months[x.name] - months[y.name]; });
Demo: http://jsfiddle.net/7eKfn/

Categories

Resources