Created
April 20, 2024 13:12
-
-
Save abusedmedia/9d47eb4d09e4374b5d8a9e71c9e1aa76 to your computer and use it in GitHub Desktop.
Handy function to get some summarization from a js array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.summarizeProperties = (data, excluded = []) => { | |
const result = {}; | |
data.forEach(obj => { | |
for (const key in obj) { | |
if (excluded.indexOf(key) === -1) { | |
let value = obj[key]; | |
let valueIsDate = false; | |
// Check if the value is a date | |
if (typeof value === 'string' && !isNaN(Date.parse(value))) { | |
valueIsDate = true; | |
} | |
if (!result[key]) { | |
if (typeof value === 'number' || valueIsDate) { | |
result[key] = { min: valueIsDate ? new Date(value) : value, max: valueIsDate ? new Date(value) : value }; | |
} else { | |
result[key] = new Set(); | |
} | |
} | |
if (result[key] instanceof Set) { | |
result[key].add(value || ''); | |
} else { | |
// Handle updating min/max for dates and numbers | |
if (valueIsDate) { | |
value = new Date(value); | |
if (value < result[key].min) { | |
result[key].min = value; | |
} | |
if (value > result[key].max) { | |
result[key].max = value; | |
} | |
} else if (typeof value === 'number') { | |
if (value < result[key].min) { | |
result[key].min = value; | |
} | |
if (value > result[key].max) { | |
result[key].max = value; | |
} | |
} | |
} | |
} | |
} | |
}); | |
// Convert all Sets to arrays | |
for (const key in result) { | |
if (result[key] instanceof Set) { | |
result[key] = Array.from(result[key]); | |
} else { | |
// Ensure date objects are converted to readable strings or kept as Date objects based on your preference | |
result[key].min = result[key].min instanceof Date ? result[key].min.toISOString() : result[key].min; | |
result[key].max = result[key].max instanceof Date ? result[key].max.toISOString() : result[key].max; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment