I have an array of objects with a date format that looks this way:
"offline_available": "5/1/2021"
As I understand it is the date formatted by the toLocaleDateString() method.
How can I sort all objects by next available date?
You need to translate your date string into a date object in the comparison function.
yourArray.sort( (a,b) => new Date(a.offline_available) - new Date(b.offline_available))
Start with this - assuming the date is mm/dd/yyyy
const arr = [
{"offline_available": "5/1/2021"},
{"offline_available": "12/13/2020"},
{"offline_available": "5/3/2020"},
{"offline_available": "5/3/2021"}
]
const sorted = arr.slice(0).sort((a,b) => new Date(a.offline_available) - new Date(b.offline_available))
console.log(sorted)
What is "sort by next available date"?
Related
My input is get via an API, and I have this array with the following date format as strings:"2022-06-29T15:30:00+00:00", "2022-07-01T09:00:00+00:00", "2022-07-05T16:00:00+00:00".
I want to transform those date in another format (ex for the first one: 29.06.2022 (DD.MM.YYYY)).
Also, I want to compare dates to sort the array. How can I do this? Do I need to convert it into a Date object? (vanilla JS, no frameworks).
You can consider doing it like this:
const str = "2022-06-29T15:30:00+00:00";
const date = new Date(str);
console.log(date); // 👉️ Wed Jun 29 2022 22:30:00
As for sorting array based on dates, you can take a look at How to sort an object array by date property.
You can first sort the dates using sort method
dateArr.sort((a, b) => new Date(a) - new Date(b))
and then map over the array
const dateArr = [
'2022-06-29T15:30:00+00:00',
'2022-07-01T09:00:00+00:00',
'2022-07-05T16:00:00+00:00',
];
const result = dateArr
.sort((a, b) => new Date(a) - new Date(b))
.map((str) => str.split('T')[0].split('-').reverse().join('-'));
console.log(result)
let dateStr = "2022-06-29T15:30:00+00:00";
let getDate = dateStr.split('T')[0];
const date = new Date(getDate);
I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"
My Slot Json Object
{
date: [
2020-06-03T00:00:00.000Z,
2020-06-05T00:00:00.000Z,
2020-06-07T00:00:00.000Z
],
__v: 0
}
I have to loop over each date in the date array and compare it with the date I get from frontend.
Let's say user input date is
let userInput = '2020-06-03';
And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for
'2020-06-03' and '2020-06-03T00:00:00.000Z'
I am looking at a solution which is appropriate when looping over all these array elements.
assuming, that your date array always is at 00:00:00 o'clock, i'd suggest something like this:
const dates = [
'2020-06-03T00:00:00.000Z',
'2020-06-05T00:00:00.000Z',
'2020-06-07T00:00:00.000Z'
];
let userInput = '2020-06-03';
function findDates(date) {
const searchDate = Date.parse(date);
const foundDates = [];
dates.forEach(date => {
const tempDate = Date.parse(date);
if (tempDate === searchDate) {
foundDates.push(date);
}
});
return foundDates;
}
console.log(findDates(userInput));
if there's more to consider, please say so
Have the format of date strings(input) and the array of dates be properly specified for parsing. Then you could straight away use the isSame() to check if the dates are equal
let input = "2020-06-03";
let arr = [
"2020-06-03T00:00:00.000Z",
"2020-06-05T00:00:00.000Z",
"2020-06-07T00:00:00.000Z"
];
let result = arr.map(item =>
moment(item, "YYYY-MM-DD hh:mm:ss zz").isSame(input, "YYYY-MM-DD")
);
console.log(result);
<script src="https://momentjs.com/downloads/moment.js"></script>
var dates = ['2017-02-01', '2017-01-01', '2016-02-03', '2018-02-02', '2014-12-25'];
var orderedDates = dates.sort(); // ['2017-01-01', '2017-02-01', '2018-02-02', '2016-02-03', '2014-12-25']
I have collection of dates(moment objects) from different year. I need to sort this dates only by 'ddMM' format (like skip years).
Is there any way to do this?
create copy of dates array, set same year for all dates - not seem like good solution.
for sorting use lodash .orderBy
You should use the 'MMDD' format and not 'DDMM'.
And it is not necessary to convert it back to a moment, since it is just to sort the array.
var orderedDates = _.orderBy(dates, e => moment(e).format('MMDD'));
You can use orderBy with an array of functions that specify your desired order (where the functions get the date and month from the moment object):
const date = (s) => moment(s, 'YYYY-MM-DD');
const dates = [date('2017-02-01'), date('2017-01-01'), date('2016-02-03'), date('2018-02-02'), date('2014-12-25')];
const result = _.orderBy(dates, [m => m.date(), m => m.month()]);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
I'm using date-fns, I can use helpers like isMonday(day) that returns true is if the day is a Monday, or isWithinRange(start, end) to check if a date is within a range, however, is there a way to return true if a date is in an array of dates?
To easy, just use Array prototype.some
const dateInArray = (date, array) => array.some(d => +d === +date);
I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.
My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
How can I grab the last and the first date in these?
I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.
var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];
function dateToNum(d) {
// Convert date "26/06/2016" to 20160626
d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}
dateData.sort(function(a,b){
return dateToNum(a) - dateToNum(b);
});
console.log( dateData );
To retrieve the first, last date:
var firstDate = dateData[0];
var lastDate = dateData[dateData.length -1];
Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.
so you're basically sorting:
20140626
20140604
20140513
20140720
resulting in:
[
"13/05/2016",
"04/06/2016",
"26/06/2016",
"20/07/2016"
]
If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates e.g. YYYY-MM-DD.
You can use localeCompare to compare strings.You can use following code to sort the dates:
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
dateData.sort(function(a, b){
var A = a.split("/");
var B = b.split("/");
var strA = [ A[2], A[1], A[0] ].join("/");
var strB = [ B[2], B[1], B[0] ].join("/");
return strA.localeCompare( strB );
});
console.log( dateData );
Once sorted, you can get the min and max dates as:
var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];
The getTime() method returns the numeric value corresponding to the
time for the specified date according to universal time. Date.getTime()
dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]
.map(a=>a.split('/').reverse().join('/'))
.sort((a,b)=>new Date(a).getTime() - new Date(b).getTime());
console.log(dateData);
A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function. The one thing I haven't seen shared is how to get the first and last dates. This should do the trick:
//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];
//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
var splitDate = date.split("/")
return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})
//sort the dates
formattedDates.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(a) - new Date(b);
});
//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];
//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)
One way I know to do this is using the .sort() function for a string. https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx
You would have to change your array into YYYY-MM-DD
then you could have the following code
var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"];
dateData.sort();
var first = dateData[0];
var last = dateData[dateData.length-1];
where first is the earliest date and last is the latest date
To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD.
This way regular sorting will get you the min and max properly, and you won't need further parsing.
Helper function to sort would be like this:
for(var i=0;i<dateData.length;++i)
{
var split = dateData[i].split("/");
dateData[i] = split.reverse().join("/");
}
Roko's answer worked for me, and +1. And Jose had a similar thought to me, +1...
...There's an easier and more robust way: .valueOf()
converting date string to number:
const dateAsNumber = new Date(dateAsString).valueOf()
JS has a built in method/function for calculating the number of milliseconds that have passed since a date; that's .valueOf(), which can be called on a Date object. So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.
After that, the normal .sort() works fine. As shown below, for your convenience:
const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];
const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());
console.log(sortedArray);
Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.