diff --git a/index.js b/index.js new file mode 100644 index 0000000..b83bb72 --- /dev/null +++ b/index.js @@ -0,0 +1,21 @@ +const sortby = (properties) => (a, b) => { + // if items is {prop1:value1, prop2:value2} + // then sort(['prop1', 'desc', 'prop2']) + // will sort by prop1 desc and prop2 + for (var i = 0; i < properties.length; i++) { + var property = properties[i] + + let order = -1 + if (i + 1 < properties.length && properties[i + 1] === 'desc') { + order = 1 + i++ + } + + if (a[property] < b[property]) return order + if (a[property] > b[property]) return -order + } + + return 0 +} + +export { sortby } \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..9a7c780 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "sortby", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..7b98eb7 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "sortby", + "description": "Sort object by property name", + "version": "1.0.0", + "author": "Frédéric Matte ", + "license": "AGPL-3.0-or-later", + "main": "index.js", + "type": "module", + "repository": { + "type": "git", + "url": "https://git.tranche.ca/fmatte/sortby" + } +}