1.4.0 • Published 8 years ago

natural-compare v1.4.0

Weekly downloads
14,258,734
License
MIT
Repository
github
Last release
8 years ago
@version    1.4.0
@date       2015-10-26
@stability  3 - Stable

Natural Compare Build Coverage

Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering".

Standard sorting:   Natural order sorting:
    img1.png            img1.png
    img10.png           img2.png
    img12.png           img10.png
    img2.png            img12.png

String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function.

Installation

  • In browser
<script src=min.natural-compare.js></script>
  • In node.js: npm install natural-compare-lite
require("natural-compare-lite")

Usage

// Simple case sensitive example
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]

// Use wrapper function for case insensitivity
a.sort(function(a, b){
  return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
})

// In most cases we want to sort an array of objects
var a = [ {"street":"350 5th Ave", "room":"A-1021"}
        , {"street":"350 5th Ave", "room":"A-21046-b"} ];

// sort by street, then by room
a.sort(function(a, b){
  return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
})

// When text transformation is needed (eg toLowerCase()),
// it is best for performance to keep
// transformed key in that object.
// There are no need to do text transformation
// on each comparision when sorting.
var a = [ {"make":"Audi", "model":"A6"}
        , {"make":"Kia",  "model":"Rio"} ];

// sort by make, then by model
a.map(function(car){
  car.sort_key = (car.make + " " + car.model).toLowerCase();
})
a.sort(function(a, b){
  return String.naturalCompare(a.sort_key, b.sort_key);
})
  • Works well with dates in ISO format eg "Rev 2012-07-26.doc".

Custom alphabet

It is possible to configure a custom alphabet to achieve a desired order.

// Estonian alphabet
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
["t", "z", "x", "õ"].sort(String.naturalCompare)
// ["z", "t", "õ", "x"]

// Russian alphabet
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// ["А", "Б", "Ё"]

External links

Licence

Copyright (c) 2012-2015 Lauri Rooden <lauri@rooden.ee>
The MIT License

eslintjest-snapshoteslint-plugin-vue@huyhpham/rn-linearchetype-libraryeasy-select-rnreact-native-bluetooth2killi8n-react-native-fast-imagepipihomespecify-importsbabel-specify-imports@supermonkey/eslint-plugin-wepy@icanpm/api-masterelectron-eslinteslint-4-fix@arisageha/react-lazyload@arisageha/react-lazyload-fix@oneplanetcrowd/developers@almeidaa/msreact-native-template-rfbaseairscanairscan-examplebb-chatreact-native-esc-pos-sahaab@borisovart/atol-kkt-moduledeneme323112@ntt_app/react-native-custom-notificationagreestudioeslintreact-native-covid-sdkgql_din_modbitgetmutasi-bca@jttechnic/interpreter@saeon/quick-formcthpb-plugin-social@iobroker-community-adapters/iobroker.device-watcher@olivervorasai/slidermysql-formatreact-native-printer-brothers@belko.tech/belko-multi-wallet-sdk@newhorizon-tech/dd-npm-package-templatereact-native-shekhar-bridge-testcogoportutilsukor-remasteruncoded-connect@skylib/eslint-plugin@reversodev/oceanic-fleetwilscanner@khalitovadel/abstract-repository@oiti/documentoscopy-react-native@respondea/cordova-plugin-v-inappbrowser@mink-opn/build-tokensquoc-testreact-native-slider-kf@atua/tokensplginveggies-tsexpand-react-bridgeopea-bootstraapluminos-ui-coresklif-ui-kitsklif-apits-handy@everything-registry/sub-chunk-2249jawwy-sdkjawwy_gamification_release@314oner_npm/universal-components-library@deepakorg/test@deepak757/testreact-native-sphereuisphereuijawwy_libraryreact-native-credit-card-pkgp149-tablesklif-uimachinebeemrcapsreact-native-jawwy_sampleswiftallyreact-lightbox-pack-18supportreact-native-animate-textreact-native-android-video-player-viewreact-native-badge-controlreact-native-basic-appreact-native-basic-screenreact-native-bubble-chartreact-native-create-video-thumbnailreact-native-cplusreact-native-build-vesion-getterdegeamunited28react-native-additionreact-native-arps-authorize-netreact-native-arun-ramya-testreact-native-arunjeyam1987react-native-arunmeena1987react-native-arunramya151react-native-bluetooth-device-detectreact-native-bleccs-componentsreact-native-biometric-authenticatereact-native-check-component
1.4.0

8 years ago

1.2.2

9 years ago