I have an array of objects that looks like the following:
[
{
"node_name": "node1",
"external": "external_node1",
"status": "online",
"Date": "2022-05-26 08:20:27.022313"
},
{
"node_name": "node2",
"external": "external_node2",
"status": "offline",
"Date": "2022-05-26 20:20:27.022313"
},
{
"node_name": "node3",
"external": "external_node3",
"status": "online",
"Date": "2022-05-26 08:20:27.022313"
},
{
"node_name": "node4",
"external": "external_node4",
"status": "online",
"Date": "2022-05-26 20:20:27.022313"
}
]
Using JavaScript, how would I 'group' and insert into its own array, all of the objects that have matching Date values?
For example, node1 & node3 both have "2022-05-26 08:20:27.022313" as its Date value, as well as node2 & node4 having the same Date value.
How would I sort these objects out and insert them into one array if the Date values matched?
You can achieve it using a combination of sort an reduce:
const data = [
{
"node_name": "node1",
"external": "external_node1",
"status": "online",
"Date": "2022-05-26 08:20:27.022313"
},
{
"node_name": "node2",
"external": "external_node2",
"status": "offline",
"Date": "2022-05-26 20:20:27.022313"
},
{
"node_name": "node3",
"external": "external_node3",
"status": "online",
"Date": "2022-05-26 08:20:27.022313"
},
{
"node_name": "node4",
"external": "external_node4",
"status": "online",
"Date": "2022-05-26 20:20:27.022313"
}
];
const result = data.sort((a,b) => Date.parse(a.Date) - Date.parse(b.Date)).
reduce((acc, data) => {
const date = data.Date;
acc[date] = acc[date] || [];
acc[date] = [...acc[date], data];
return acc;
}, {})
console.log(result);
I would suggest using Array.reduce() to convert the input to the desired form.
You can wrap this in a groupBy() function. This will return an object with an array of objects for each value encountered.
const input = [ { "node_name": "node1", "external": "external_node1", "status": "online", "Date": "2022-05-26 08:20:27.022313" }, { "node_name": "node2", "external": "external_node2", "status": "offline", "Date": "2022-05-26 20:20:27.022313" }, { "node_name": "node3", "external": "external_node3", "status": "online", "Date": "2022-05-26 08:20:27.022313" }, { "node_name": "node4", "external": "external_node4", "status": "online", "Date": "2022-05-26 20:20:27.022313" } ]
function groupBy(arr, key) {
return arr.reduce((acc, el) => {
acc[el[key]] = [...(acc[el[key]] || []), el];
return acc;
}, {})
}
const result = groupBy(input, 'Date');
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
Use javascript's .filter() method.
const newArray = oldArray.filter(data => {
return data.Date == "2022-05-26 08:20:27.022313"
})
This will return all the objects with date value as above (2022-05-26 08:20:27.022313) i.e. node1 and node3 into a different array.