I use this function to order nested arrays of objects (JSON) in Javascript (English isnt my native lang)
nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
const a = prop2 ? e1[prop1][prop2] : e1[prop1],
b = prop2 ? e2[prop1][prop2] : e2[prop1],
sortOrder = direction === "asc" ? 1 : -1
return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
}
previously i cleaned all the null values of the array with this function
array = JSON.parse(JSON.stringify(array), (key, value) => value === null ? '' : value);
the trouble im having is that is only ordering string values and date values, the numerical values are treated like strings, i need some advice on what can i add to the nestedSort function to work dinamically ordering : strings, dates, and numerical values?
i call the function with this code
objJson = objJson.sort(nestedSort(value, null, records_order));
[Solved] Idk if it was the best way, i will appreciate if someone has a better way to do it
nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
const a = prop2 ? e1[prop1][prop2] : e1[prop1],
b = prop2 ? e2[prop1][prop2] : e2[prop1],
sortOrder = direction === "asc" ? 1 : -1
if (isNaN(a) && isNaN(b)){
return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
}else{
return sortOrder == 1 ? (a - b) : (b - a);
}
}