sort-object-entries
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

sort-object-entries

License Sponsor sort-object-entries
Build status Commits since v1.0.0 Last commit Issues
Latest version on npm Dependents Downloads

Sorts an object's entries. Order can be determined by both keys and properties.

The compare function has 4 parameters and should return a number: compare(value1, value2, key1, key2).

Installation

sort-object-entries on npm

npm install --save sort-object-entries@^1.0.0

sort-object-entries on Yarn

yarn add sort-object-entries@^1.0.0

Example

const object = {
  mark: {
    age: 22,
  },
  tom: {
    age: 17,
  },
  sarah: {
    age: 13,
  },
  dwight: {
    age: 22,
  },
  bill: {
    age: 37,
  },
}
 
// Older people first, a-z on same age
function compare(value1, value2, key1, key2) {
  if (value1.age > value2.age) {
    return 1
  }
  if (value2.age > value1.age) {
    return -1
  }
  return new Intl.Collator("en").compare(key1, key2)
}
 
const result = sortObjectEntries(object, compare)
 

Variable result will now be:

{
  bill: {
    age: 37,
  },
  dwight: {
    age: 22,
  },
  mark: {
    age: 22,
  },
  tom: {
    age: 17,
  },
  sarah: {
    age: 13,
  },
}

Development

Setting up:

git clone git@github.com:jaid/sort-object-entries.git
cd sort-object-entries
npm install

Testing:

npm run test:dev

Testing in production environment:

npm run test

License

MIT License
 
Copyright © 2020, Jaid <jaid.jsx@gmail.com> (github.com/jaid)
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Readme

Keywords

none

Package Sidebar

Install

npm i sort-object-entries

Weekly Downloads

2

Version

1.0.0

License

none

Unpacked Size

7.85 kB

Total Files

5

Last publish

Collaborators

  • jaid