Having an array of dictionaries I'd like to obtain the most updated record. For instance, consider the following record:
var myArray = [{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
}}];
which then I would need to get the most updated record first:
myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());
However, I am not getting the correct result. Would you know how to get it working?
Thanks :)
I have refactored your code a little bit.
first of all, your myArray contains only one object. you cannot sort an object like that. therefore I change the structure of your array.
here is a working example:
var myArray = [
{
id: 1,
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
id: 2,
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
id: 3,
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());
console.log(myArray)
This snippet should help you:
const myArray = [
{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
}
}
];
const sortedArray = myArray.map(entry => {
let tmpObj = {};
let tmpSorted = Object.keys(entry).sort((prev, next) => {
return Date.parse(entry[next]?.date) - Date.parse(entry[prev]?.date);
});
tmpSorted.forEach(e => {
tmpObj[e] = entry[e];
})
return tmpObj;
});
console.log(sortedArray);
Your current approach attempts to sort an array of length 1, and the item in the array is an object that represents each record as a property (another object). This makes it a bit inefficient to iterate over your data. Do you need the ItemA labeling for each record and, if so, why not make this part of the object describing the record itself along with date and name?
You can look at Object.entries(), Object.keys(), or Object.values() for ways to make use of object data in an array in order to sort or map over your data.
Assuming your current schema and assuming you had an array with many such objects, if you wanted to find the most recent record in the list for some item i in your array, here is a solution.
You can create a sorted array of objects representing each record for the array item in question. Once sorted, you can take the first or last record to get the oldest or newest. See example below.
const myArray = [
{
itemA: {
name: "Joe Blow",
date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
},
itemC: {
name: "John Smith",
date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
},
itemB: {
name: "Sam Snead",
date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
}
}
];
const sortedEntries = myArray.map((entry) => {
const records = Object.values(entry);
const sortedRecords = records.sort(function (prev, next) {
return new Date(prev.date) < new Date(next.date) ? -1 : 1;
});
return sortedRecords;
});
// the array with records for each entry now sorted as an array from oldest to most recent date
console.log("sorted entries: ", sortedEntries);
// for example purposes, accessing your array by index, assuming you had more than 1 item in the array
const i = 0;
// get the record with most recent date for this array item
console.log(
"most recent record for example entry is: ",
sortedEntries[i][sortedEntries[i].length - 1]
);
https://codesandbox.io/s/festive-shadow-s36cf3
If you want to find the record with the latest date, you can iterate through the collection and store a record if it satisfies the comparator.
const
identityFn = (x) => x,
findBy = (collection, accessor, comparator) => {
let result, prev, record, i;
if (collection && collection.length) {
for (i = 0; i < collection.length; i++) {
record = collection[i];
if (!prev || comparator(accessor(record), prev)) {
result = record;
prev = accessor(record);
}
};
}
return result;
},
findMax = (collection, accessor = identityFn) =>
findBy(collection, accessor, (curr, prev) => curr > prev);
const
myArray = [{
itemA: { name: "Joe Blow" , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
itemB: { name: "Sam Snead" , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
itemD: { name: "Jane Doe" , date: null },
itemE: null,
}],
extractDate = (data) => data ? new Date(data?.date) : null,
[key, record] = findMax(
Object.entries(myArray[0]), // Access the entries (key/val pairs)
([key, val]) => extractDate(val) // Map the parsed date
);
console.log(record); // Data for key "itemC"
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to sort the records, you can modify the code above like so:
const sortBy = (collection, accessor, comparator) =>
collection.sort((a, b) => comparator(accessor(a), accessor(b)));
const
myArray = [{
itemA: { name: "Joe Blow" , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
itemB: { name: "Sam Snead" , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
itemD: { name: "Jane Doe" , date: null },
itemE: null,
}],
extractDate = (data) => data ? new Date(data?.date) : null,
sorted = sortBy(
Object.entries(myArray[0]), // Access the entries (key/val pairs)
([key, val]) => extractDate(val), // Map the parsed date
(curr, prev) => prev - curr // Same as (DESC): (curr - prev) * -1
);
console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Edit
Added null values
Changed ([key, { date }]) => new Date(date) to ([key, val]) => extractDate(val) to handle null values
Related
I am experiencing an issue while updating an object in my ReactJS application. I am using a map statement to change the partition key of an object, but the final object still contains the original partition key. The expected behavior is for the partition key to be updated. I have included my code below, as well as the actual and desired output. Can you help me understand why the partition key is not being updated and how I can resolve this issue?
this.state = {
keyb: 0,
clockVisiblity:false,
partitions:[
{id:1,name:"P1"},
{id:2,name:"P2"},
{id:3,name:"P3"},
],
dayDetails:[
{
"day":"Monday",
"full_day":false,
"partition":1,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
},
],
activePartition:1,
}
setPartitionsDetails=()=>{
var partitionData = this.state.dayDetails.find((item)=>item.partition===this.state.activePartition)
const dayDetails = this.state.partitions.map((partition) => {
partitionData.partition=partition.id
console.log("You object ",partitionData)
return partitionData
}
)
}
final object of daydetails comes:
[
{
"day":"Monday",
"full_day":false,
"partition":3,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
},
{
"day":"Monday",
"full_day":false,
"partition":3,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
},
{
"day":"Monday",
"full_day":false,
"partition":3,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
}
]
where as the desire object containers unique or different partition key.
[
{
"day":"Monday",
"full_day":false,
"partition":1,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
},
{
"day":"Monday",
"full_day":false,
"partition":2,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
},
{
"day":"Monday",
"full_day":false,
"partition":3,
"start_time":"Thu Sep 01 2022 18:47:09 GMT+0500 (PKT)"
}
]
This is occurring because you're using the same instance of partitionData to write the value of partition, so 2 is overwritten on 1 and 3 is overwritten on 2, and you get 3 in all the instances, you can fix this by making clone of partitionData and return that clone after updating.
const dayDetails = this.state.partitions.map((partition) => {
let partitionDataClone = {...partitionData};
partitionDataClone.partition = partition.id
return partitionDataClone;
})
As the partition is on the first level of this object, so the shallow cloning works here, but for nested objects, you should consider deep cloning.
It's because your mapping the partitions so you will only have the last value, which is 3. What you could do to make sure you only use one ID is to use splice.
const setPartitionsDetails = () => {
const partitionCollection = [...this.state.partitions];
this.state.dayDetails.forEach((_, index) => {
var partitionData = this.state.dayDetails[index];
if (partitionCollection.length) {
partitionData.partition = partitionCollection.splice(0, 1)[0].id;
}
});
};
I have the following data.
{
status: "Reserved",
label: "Note",
title: "Login Fragment - Navigation component With Coroutine ",
shareWith: "",
notification_method: "Every Morning",
notification_method_specific_time: Sat Jan 09 2021 00:00:00 GMT+0700 (Western Indonesia Time),
noteDetails: Array(2)
0:
completed_date: ""
description: "Test 1"
due_date: Sat Jan 09 2021 20:00:00 GMT+0700 (Western Indonesia Time) {}
__proto__: Object
1:
completed_date: ""
description: "Test 2"
due_date: Sun Jan 10 2021 20:15:00 GMT+0700 (Western Indonesia Time) {}
__proto__: Object
length: 2
__proto__: Array(0)
}
The case is how to convert from Date format (object) to date string?
notification_method_specific_time
due_date: Sun Jan 10 2021 20:15:00 GMT+0700 (Western Indonesia Time) (in array)
My data is obtained from the onSubmit React Hook, and so far I have succeeded in point number one, as follows:
const convertDate = (date) => {
return date ? moment(date).format('YYYY-MM-DD HH:mm') : null;
}
const onSubmit = (data) => {
const formData = {
...data,
notification_method_specific_time: convertDate(data.notification_method_specific_time),
}
console.log(formData);
// notification_method_specific_time: "2021-01-09 00:00"
}
But what about the date (due_date) element in the array, please help.
You need to map in your noteDetails and convert the due_date
const formData = {
...data,
notification_method_specific_time: convertDate(data.notification_method_specific_time),
noteDetails: data.noteDetails.map(note => ({
...note,
due_date: convertDate(note.due_date)
})
}
I have been trying to take the json data outputted from the database and create an new array that groups the data by month and year.
The problem is my new array doesn't output in the format that i need so i need to add the month and year but can't get the month grouping to work first. I think that might be right and resolve my issue, but I need help as arrays are confusing.
I have a codepen demo https://codepen.io/james182/pen/yLaqybP
var data = [
{ name: "First", timestampSent: "Wed, 25 Nov 2020 - 11:01 AM" },
{ name: "Second", timestampSent: "Wed, 25 Nov 2020 - 11:21 AM" },
{ name: "Third", timestampSent: "Thu, 26 Nov 2020 - 10:21 AM" },
{ name: "Fourth", timestampSent: "Fri, 27 Nov 2020 - 13:52 PM" },
{ name: "Fifth", timestampSent: "Tue, 24 Dec 2020 - 11:01 AM" },
{ name: "Sixth", timestampSent: "Wed, 25 Dec 2020 - 01:01 AM" }
];
// Clear console before running
console.clear();
var list = [];
for (i = 0; i < data.length; i++) {
var dates = data[i].timestampSent.slice(5, 16);
var mth = data[i].timestampSent.split(" ")[2];
if (!list[mth]) {
list[mth] = [];
}
list[mth].push({ name: data[i].name, date: data[i].timestampSent });
console.log(mth);
}
console.log(JSON.stringify(list));
//console.log('list', list);
/*
outcome:
[{
'Nov': [
{
'name': 'First',
'timestampSent': 'Wed, 25 Nov 2020 - 11:01 AM'
},
{
'name': 'Second',
'timestampSent': 'Wed, 25 Nov 2020 - 11:21 AM'
},
{
'name': 'Third',
'timestampSent': 'Thu, 26 Nov 2020 - 10:21 AM'
},
{
'name': 'Fourth',
'timestampSent': 'Fri, 27 Nov 2020 - 13:52 PM'
}
],
'Dec': [
{
'name': 'Fifth',
'timestampSent': 'Tue, 24 Dec 2020 - 11:01 AM'
},
{
'name': 'Sixth',
'timestampSent': 'Wed, 25 Dec 2020 - 01:01 AM'
}
]
}]
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Your list should not be an array. Since you are using the month name ('Nov', 'Dec') as keys you should use an object.
var list = {};
try change the line
list = []
to
list = {}
You will be using an object, not a list.
Try it here
I have the following structure on my firebase database:
I need to get an array of all the data with a special structure. This is how I do it:
const isObject = obj => {
return Object.prototype.toString.call(obj) === '[object Object]' ? true : false;
};
function snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
if (isObject(item)){
returnArr = returnArr.concat(snapshotToArray(childSnapshot));
}
});
return returnArr;
};
And call it:
snapshotToArray(snapshot); // 'snapshot' is the data from database in a snapshot format
Getting:
[ { 'Diciembre-2018': { '-LJV5UxepDNSR5yUCDbf': [Object] },
'Julio-2018': { '-LJUt8yTjpK3oq2wRd_g': [Object] },
key: '2018' },
{ '-LJV5UxepDNSR5yUCDbf':
{ pin: 'mi-pin-dic',
timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)' },
key: 'Diciembre-2018' },
{ pin: 'mi-pin-dic',
timestamp: 'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
key: '-LJV5UxepDNSR5yUCDbf' },
'mi-pin-dic',
'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
{ '-LJUt8yTjpK3oq2wRd_g':
{ pin: 'mi-pin-julio',
timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' },
key: 'Julio-2018' },
{ pin: 'mi-pin-julio',
timestamp: 'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)',
key: '-LJUt8yTjpK3oq2wRd_g' },
'mi-pin-julio',
'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)' ]
But as you can see, in the 3rd and 5th iteration it gets an extra data:
'mi-pin-dic',
'Thu Aug 09 2018 13:11:39 GMT-0600 (GMT-06:00)',
'mi-pin-julio',
'Thu Aug 09 2018 12:13:21 GMT-0600 (GMT-06:00)'
My question:
How can I avoid this issue? Any ideas?
Given the following array of objects, I need to ascending sort them by the date field.
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
In the above example, the final result would be John Smith, Sam Snead, and Joe Blow.
I am trying to use lodash's _.sortBy(), but I can't get any sorting to take place no matter how I try to use it:
_.sortBy(myArray, function(dateObj) {
return dateObj.date;
});
or
_.sortBy(myArray, 'date');
What do I need to change to get my array sorted properly? I also have Moment.js, so I can use it to format the date string if needed. I tried converting the date property using .unix(), but that didn't make a difference.
Thanks.
You don't really need lodash. You can use JavaScript's Array.prototype.sort method.
You'll need to create Date objects from your date strings before you can compare them.
var myArray = [{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
}, {
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
}, {
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}];
myArray.sort(function compare(a, b) {
var dateA = new Date(a.date);
var dateB = new Date(b.date);
return dateA - dateB;
});
console.log(myArray);
Here's a solution using standard Javascript by converting both values to date object and comparing their value.
myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
A complete snippet:
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
console.log(myArray);
Your date values are strings, so you need to use the new Date() constructor to change them to javascript date objects. This way you can sort them (using _.sortBy).
var myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray = _.sortBy(myArray, function(dateObj) {
return new Date(dateObj.date);
});
console.log(myArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
If you are trying to use lodash to sort dates in ascending or descending order for your array of objects, you should use _.orderBy instead of _.sortBy
https://lodash.com/docs/4.17.15#orderBy, this method allows specifying sort orders either by 'asc' or 'desc'
An example would be:
const sortedArray = _(myArray.orderBy([
function(object) {
return new Date(object.date);
}],["desc"])
A cleaner way using Lodash orderBy:
import _ from 'lodash'
const sortedArray = _.orderBy(myArray, [(obj) => new Date(obj.date)], ['asc'])
just write _.sortBy({yourCollection}, {the field name});
lodash will automatically figure that this is a date and it'll work like a magic!
Awesome!
Inspired by others answers and noticing that you used moment.js and lodash, you can combine both with _.orderBy lodash method:
import moment from 'moment'
import * as _ from 'lodash'
let myArray = [
{
name: "Joe Blow",
date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "Sam Snead",
date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
},
{
name: "John Smith",
date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"
}
];
myArray = _.orderBy(myArray, [(item) => {
return moment(item.date).format('YYYY-MM-DD')
}], ['desc'])
this has worked for me
myArray = _.orderBy(myArray, [item => item.lastModified], ['desc']);