1

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);
        }
}
Olddevman
  • 29
  • 3
  • yes, JS sorts numbers as strings. You need to cast them to actual numbers. See https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly – kca Apr 22 '22 at 22:03
  • The OP should give the [`numeric` sorting option](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#numeric_sorting) of [`String.prototype.localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) a try ... see also ... [_"How to sort an array of objects correctly by an object's alphanumeric name value?"_](https://stackoverflow.com/questions/71699814/how-to-sort-an-array-of-objects-correctly-by-an-objects-alphanumeric-name-value/71700078#71700078) – Peter Seliger Apr 22 '22 at 22:12
  • Thank you Peter and Kca, I solved it thank to your tips i will edit the question – Olddevman Apr 24 '22 at 00:19

0 Answers0