12 June 2024

In JavaScript, you can sort arrays of objects by a specified property using custom functions that handle both string and integer properties, and can sort in either ascending or descending order. The sortByString function uses localeCompare for comparing string properties, while sortByInteger performs numerical comparisons for integer properties. Both functions accept an order parameter that determines the sort direction, with 'asc' for ascending and 'desc' for descending.

Source code viewer
  1. const ASCENDING = 'asc';
  2. const DESCENDING = 'desc';
  3.  
  4. // Function to sort by string property with order and undefined handling
  5. function sortByString(arr, key, order = ASCENDING) {
  6. return arr.sort((a, b) => {
  7. if (a[key] === undefined) return 1;
  8. if (b[key] === undefined) return -1;
  9. const result = a[key].localeCompare(b[key]);
  10. return order === DESCENDING ? -result : result;
  11. });
  12. }
  13.  
  14. // Function to sort by integer property with order and undefined handling
  15. function sortByInteger(arr, key, order = ASCENDING) {
  16. return arr.sort((a, b) => {
  17. if (a[key] === undefined) return 1;
  18. if (b[key] === undefined) return -1;
  19. const result = a[key] - b[key];
  20. return order === DESCENDING ? -result : result;
  21. });
  22. }
  23.  
  24. const peopleWithUndefined = [
  25. { name: 'Alice', age: 25 },
  26. { name: 'Bob', age: undefined },
  27. { name: 'Charlie', age: 20 },
  28. { name: undefined, age: 30 }
  29. ];
  30.  
  31. // Sort by name (string property) in ascending order
  32. const sortedByNameAsc = sortByString([...peopleWithUndefined], 'name', ASCENDING);
  33. console.log('Sorted by name (asc):', sortedByNameAsc);
  34.  
  35. // Sort by name (string property) in descending order
  36. const sortedByNameDesc = sortByString([...peopleWithUndefined], 'name', DESCENDING);
  37. console.log('Sorted by name (desc):', sortedByNameDesc);
  38.  
  39. // Sort by age (integer property) in ascending order
  40. const sortedByAgeAsc = sortByInteger([...peopleWithUndefined], 'age', ASCENDING);
  41. console.log('Sorted by age (asc):', sortedByAgeAsc);
  42.  
  43. // Sort by age (integer property) in descending order
  44. const sortedByAgeDesc = sortByInteger([...peopleWithUndefined], 'age', DESCENDING);
  45. console.log('Sorted by age (desc):', sortedByAgeDesc);
Programming Language: ECMAScript