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
const ASCENDING = 'asc'; const DESCENDING = 'desc'; // Function to sort by string property with order and undefined handling function sortByString(arr, key, order = ASCENDING) { return arr.sort((a, b) => { if (a[key] === undefined) return 1; if (b[key] === undefined) return -1; const result = a[key].localeCompare(b[key]); return order === DESCENDING ? -result : result; }); } // Function to sort by integer property with order and undefined handling function sortByInteger(arr, key, order = ASCENDING) { return arr.sort((a, b) => { if (a[key] === undefined) return 1; if (b[key] === undefined) return -1; const result = a[key] - b[key]; return order === DESCENDING ? -result : result; }); } const peopleWithUndefined = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: undefined }, { name: 'Charlie', age: 20 }, { name: undefined, age: 30 } ]; // Sort by name (string property) in ascending order const sortedByNameAsc = sortByString([...peopleWithUndefined], 'name', ASCENDING); console.log('Sorted by name (asc):', sortedByNameAsc); // Sort by name (string property) in descending order const sortedByNameDesc = sortByString([...peopleWithUndefined], 'name', DESCENDING); console.log('Sorted by name (desc):', sortedByNameDesc); // Sort by age (integer property) in ascending order const sortedByAgeAsc = sortByInteger([...peopleWithUndefined], 'age', ASCENDING); console.log('Sorted by age (asc):', sortedByAgeAsc); // Sort by age (integer property) in descending order const sortedByAgeDesc = sortByInteger([...peopleWithUndefined], 'age', DESCENDING); console.log('Sorted by age (desc):', sortedByAgeDesc);Programming Language: ECMAScript