From e4cdd2592243934b3109a024059d45ddab1f7cab Mon Sep 17 00:00:00 2001 From: James Collins Date: Wed, 22 Feb 2023 20:22:49 +1000 Subject: [PATCH] added sortProperties method --- resources/js/helpers/object.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 resources/js/helpers/object.ts diff --git a/resources/js/helpers/object.ts b/resources/js/helpers/object.ts new file mode 100644 index 0000000..efa73a2 --- /dev/null +++ b/resources/js/helpers/object.ts @@ -0,0 +1,29 @@ +/** + * Sort a objects properties alphabetically + * + * @param {Record} obj The object to sort + * @returns {Record} The object sorted + */ +export const sortProperties = ( + obj: Record +): Record => { + // convert object into array + const sortable: [string, unknown][] = []; + for (const key in obj) + if (Object.prototype.hasOwnProperty.call(obj, key)) + sortable.push([key, obj[key]]); // each item is an array in format [key, value] + + // sort items by value + sortable.sort(function (a, b) { + const x = String(a[1]).toLowerCase(), + y = String(b[1]).toLowerCase(); + return x < y ? -1 : x > y ? 1 : 0; + }); + + const sortedObj: Record = {}; + sortable.forEach((item) => { + sortedObj[item[0]] = item[1]; + }); + + return sortedObj; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ] +};