Created
September 18, 2022 00:55
-
-
Save aminechraibi/04945844600195cb7efb25a7eecb3f26 to your computer and use it in GitHub Desktop.
Get stats of an array of objects (not nested)
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
const COUNT_REST_NAME = "other+" | |
function getColumnsFromJson(json) { | |
return [...new Set(json.reduce(function (keys, element) { | |
for (let key in element) { | |
keys.push(key); | |
} | |
return keys; | |
}, []))]; | |
} | |
function jsonStats(json, columns, specificsValues) { | |
let allColumns = getColumnsFromJson(json) | |
columns ??= allColumns | |
let stats = {} | |
specificsValues ??= {} | |
for (const column of columns) { | |
if (allColumns.includes(column)) { | |
if (specificsValues.hasOwnProperty(column)) { | |
let countedValues = specificsValues[column]; | |
let columnStats = {} | |
for (const jsonElement of json) { | |
let jsonColumnValue = jsonElement[column] | |
if (countedValues.includes(jsonElement[column])) { | |
columnStats[jsonColumnValue] = (columnStats[jsonColumnValue] || 0) + 1 | |
} else if (countedValues.includes(COUNT_REST_NAME)) { | |
columnStats[COUNT_REST_NAME] = (columnStats[COUNT_REST_NAME] || 0) + 1 | |
} | |
} | |
stats[column] = columnStats; | |
} else { | |
stats[column] = json.reduce(function (sums, entry) { | |
sums[entry[column]] = (sums[entry[column]] || 0) + 1; | |
return sums; | |
}, {}); | |
} | |
} | |
} | |
return stats | |
} | |
// examples: | |
let data = [ | |
{id:"1","name":"Test","isGood":true}, | |
{id:"2","name":"Test 1","isGood":true}, | |
{id:"3","name":"Test 2","isGood":false}, | |
{id:"4","name":"Test 3","isGood":false}, | |
{id:"4","name":"Test 3","isGood":true}, | |
{id:"4","name":null,"isGood":true}, | |
]; | |
console.log(jsonStats(data)) | |
/* | |
{ | |
"id": { | |
"1": 1, | |
"2": 1, | |
"3": 1, | |
"4": 3 | |
}, | |
"name": { | |
"Test": 1, | |
"Test 1": 1, | |
"Test 2": 1, | |
"Test 3": 2, | |
"null": 1 | |
}, | |
"isGood": { | |
"true": 4, | |
"false": 2 | |
} | |
} | |
*/ | |
console.log(jsonStats(data, ["name", "isGood"])) | |
/* | |
{ | |
"name": { | |
"Test": 1, | |
"Test 1": 1, | |
"Test 2": 1, | |
"Test 3": 2, | |
"null": 1 | |
}, | |
"isGood": { | |
"true": 4, | |
"false": 2 | |
} | |
} | |
*/ | |
console.log(jsonStats(data, ["name", "isGood"],{"name":[null,COUNT_REST_NAME]})) | |
/* | |
{ | |
"name": { | |
"other+": 5, | |
"null": 1 | |
}, | |
"isGood": { | |
"true": 4, | |
"false": 2 | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment