diginext-utils
Version:
README.md
37 lines • 1.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortByString = sortByString;
/**
* Sorts an array of objects by a string property in ascending order.
* Creates a new sorted array without modifying the original.
*
* @template T - The type of elements in the array
* @param array - The array to sort
* @param key - The property key to sort by
* @returns A new sorted array
*
* @example
* ```ts
* const users = [
* { name: 'Charlie' },
* { name: 'Alice' },
* { name: 'Bob' }
* ];
* sortByString(users, 'name');
* // [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }]
* ```
*/
function sortByString(array, key) {
if (!Array.isArray(array)) {
return [];
}
return [...array].sort((a, b) => {
var _a, _b;
const valueA = String((_a = a[key]) !== null && _a !== void 0 ? _a : "").toUpperCase();
const valueB = String((_b = b[key]) !== null && _b !== void 0 ? _b : "").toUpperCase();
if (valueA === valueB)
return 0;
return valueA > valueB ? 1 : -1;
});
}
//# sourceMappingURL=sortByString.js.map