i am getting below array.
Array [
"מאי 2017",
"יוני 2017",
"ינואר 2018",
"פברואר 2018",
"מרץ 2018",
"מאי 2018",
"יוני 2018",
"נובמבר 2019",
"אוגוסט 2020",
"נובמבר 2020",
"דצמבר 2020",
"ינואר 2021",
]
and i have an english month array.
const englishMonthArray = [
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
how can i match only months of above array with English months?Thanks
Create a dictionary object that maps the Hebrew month (key) to the English equivalent (value).
map over the array. split the string on the space, get the English month from the dictionary, and then return a new string.
const arr=["מאי 2017","יוני 2017","ינואר 2018","פברואר 2018","מרץ 2018","מאי 2018","יוני 2018","נובמבר 2019","אוגוסט 2020","נובמבר 2020","דצמבר 2020","ינואר 2021"];
const dict = {
ינואר: 'January',
פברואר: 'February',
מרץ: 'March',
אַפּרִיל: 'April',
מאי: 'May',
יוני: 'June',
יולי: 'July',
אוגוסט: 'August',
יולי: 'September',
יולי: 'October',
נובמבר: 'November',
דצמבר: 'December'
};
const out = arr.map(el => {
// This was interesting. For an English string
// this would be destructured like [year, month].
// I'm assuming that because there's Hebrew in the string
// JS/the browser reads it differently (right to left).
const [ month, year ] = el.split(' ');
const enMonth = dict[month];
return `${year} ${enMonth}`;
});
console.log(out);
Additional documentation
Template/string literals
Destructuring assignment
Related
I have a string "APRIL,AUGUST,JULY,JUNE,MAY". I want to order it by month name.
The required output is APRIL,MAY,JUNE,JULY,AUGUST.
You can keep order list of all months and do the sorting based on that:
const order = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
const sort = (data) =>
data
.split(',')
.sort((a, b) => order.indexOf(a) - order.indexOf(b))
.join()
const data1 = 'APRIL,AUGUST,JULY,JUNE,MAY'
console.log(sort(data1))
const data2 = 'APRIL,AUGUST,JULY,JUNE,MAY,APRIL'
console.log(sort(data2))
The easiest solution is probably:
const s = "APRIL,AUGUST,JULY,JUNE,MAY";
const months = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "OCTOBER", "SEPTEMBER", "NOVEMBER", "DECEMBER"]
let resultArray = [];
months.forEach(month => {
if (s.includes(month)) {
resultArray.push(month);
}
})
console.log(resultArray.join(','));
Use Array#filter() on preordered array and check if each name exists in the string
const s = "APRIL,AUGUST,JULY,JUNE,MAY";
const months = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "OCTOBER", "SEPTEMBER", "NOVEMBER", "DECEMBER"]
const res = months.filter(m => s.includes(m)).join()
console.log(res)
The other solutions might be inefficient because they rely on the String.includes or Array.indexOf prototypes, which cost alone O(n) (where n is the length of the input string).
I propose an alternative solution that uses a dictionary, which supports indexing in amortized O(1) time.
The overall time complexity is O(m logm), where m is the number of months in the input string.
You can index month names in monthNamesObj in amortized O(1) time.
const input = "APRIL,AUGUST,JULY,JUNE,MAY";
// inputMonthNames = ['APRIL', 'AUGUST', 'JULY', 'JUNE', 'MAY']
const inputMonthNames = input.split(',');
// dictionary that maps month names to the correspective order index
const monthNamesObj = {
'JANUARY': 0,
'FEBRUARY': 1,
'MARCH': 2,
'APRIL': 3,
'MAY': 4,
'JUNE': 5,
'JULY': 6,
'AUGUST': 7,
'SEPTEMBER': 8,
'OCTOBER': 9,
'NOVEMBER': 10,
'DECEMBER': 11,
};
// sort the input month names according to their numeric order
const orderedMonths = inputMonthNames.sort((a, b) => monthNamesObj[a] - monthNamesObj[b]);
// APRIL,MAY,JUNE,JULY,AUGUST
console.log(orderedMonths.join(','));
I have a string like "August 24th, 2020" that I need to convert into the "Date" type in Angular. Is there any simple way to do this please?
I've tried this:
const deadline = new Date ("August 24th, 2020")
But that results in "Invalid Date".
Maybe moment.js is capable to parse that outside of the box, however, if you're not willing to attach external library and maintain its compatibility to the rest of your environment for this purpose only, you may parse that yourself:
const dateStr = "August 24th, 2020",
parseDate = s => {
const [, month, dd, yyyy] = s.match(/([a-z]+)\s(\d+)[a-z]+,\s(\d+)/i)||[],
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
return new Date(Date.UTC(yyyy, months.indexOf(month), dd))
}
console.log(parseDate(dateStr))
I am trying to control "Month" and "Year" in drop down list. I am having two fields, "Start Date" and "End Date". In that "Start Date" I am listing the "Current Month" and "Year" like "March 2020". I want to control my "End Date" based of "Start Date". For example if there is no "Month" selected in "Start Date" I should not allow user to select the "End Date". If user select's "MAY 2020" in "Start Date" and in "End Date" I want to display from "May 2020 to next May 2021". Like wise if user select's "June 2020" in "Start Date" and in "End Date" I want to display from "June 2020 to next June 2021". As of now I am displaying the current month and year in both Start and End date. Any one can guide me to achieve this. Thanks in Advance. Below is the code where I am getting current year month to next year.
const fareMon = () => {
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const currDate = new Date();
const year = currDate.getFullYear();
const months = [];
let currentMonthIndex = currDate.getMonth();
let yearsToAdd = 0;
for (let i = 0; i < 13; i += 1) {
if (currentMonthIndex === 12) {
currentMonthIndex = 0;
yearsToAdd += 1;
}
const futYear = year + yearsToAdd;
months.push(<option value={`${monthList[currentMonthIndex]} ${futYear}`}>{`${monthList[currentMonthIndex]} ${futYear}`}</option>);
currentMonthIndex += 1;
}
return <>{months}</>;
};
So, what I have done is, created a getFullYear function, where you can pass year and you will get all the months
Does this help:
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const getFullYear = (year) => {
const currentDate = new Date(`01 01 ${year}`);
const monthYear = [];
for(;currentDate.getFullYear() === year;){
const currentMonth = currentDate.getMonth();
monthYear.push(`${monthList[currentMonth]} ${year}`)
const nextMonth = currentMonth+1;
currentDate.setMonth(nextMonth);
}
return monthYear;
}
More cleaner and less compute intensive approach would be:
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const getYear = (year) => {
return monthList.map((month) => `${month} ${year}`);
}
hello my question is how to get last four months records from database.i got the output but not getting my expected pattern so how to do this can any one help me to solve this.
db.Air_pollution.aggregate([
{$match:
{CREATE_DATE:{$lte:new Date(),
$gte:new Date(new Date().setDate(new
Date().getDate()-120))}}},
{
$group:
{
_id:{month:{$month:"$CREATE_DATE"},
year:{$year:"$CREATE_DATE"}
},
avgofozone:{$avg:"$OZONE"}
}
},
{
$sort:{"year":-1}
},
{
$project:{
year:'$_id.year',
avgofozone:'$avgofozone',
month:'$_id.month',_id:0
}
}
])
Output is:
{ "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 3 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 1 }
Expected output:
zone_type year january febravary march
avgofozone 2018 17.8 21.07777 17.8
You already have the data you need, rather than trying to get it exactly how you need it from MongoDB, why not just format it in the application layer?
Some simple JavaScript to do that:
const months = [
'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December'
];
function monthNumToName(monthnum) {
return months[monthnum - 1];
}
const results = [{
"avgofozone": 21.07777777777778,
"year": 2018,
"month": 2
}, {
"avgofozone": 17.8,
"year": 2018,
"month": 3
}, {
"avgofozone": 17.8,
"year": 2018,
"month": 1
}];
const statsByYear = results.reduce((a, c) => {
const {
year,
month,
avgofozone
} = c;
if (!a[year])
a[year] = {
zone_type: 'avgofozone',
year,
[monthNumToName(month)]: avgofozone
}
else a[year][monthNumToName(month)] = avgofozone
return a;
}, {});
const formatted = Object.keys(statsByYear).map(k => {
return statsByYear[k];
});
console.log(formatted);
I am formatting dates using moment.js with arabic locale (ar_SA) set.
moment.locale('ar_SA');
moment([2016,05,01]).format('MMM YYYY');
//output مايو ٢٠١٦
I would like to format only the month part using the locale, but the year in english, example: "مايو 2016" (the same as when formatting using the angular filter: | date:'MMM yyyy')
Is there a way to configure moment.js to do this automatically? (instead of splitting the month and year formatting and simply concatenating 2016 to .format('MMM'))
moment.updateLocale('en', {
months : [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
});
Source: https://momentjs.com/docs/#/customization/month-names/
I never did find a solution to this. I opted for a split/manual approach instead:
currentDate.format('MMM') + ' ' + currentDate.clone().locale('en').format('YYYY');