3.0.1 • Published 4 years ago

string-natural-compare v3.0.1

Weekly downloads
1,318,263
License
MIT
Repository
github
Last release
4 years ago

String Natural Compare

NPM Version Build Status Coverage Status Dependencies Status

Compare alphanumeric strings the same way a human would, using a natural order algorithm (originally known as the alphanum algorithm) where numeric characters are sorted based on their numeric values rather than their ASCII values.

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

This module exports a function that returns a number indicating whether one string should come before, after, or is the same as another string. It can be used directly with the native .sort() array method.

Fast and Robust

This module can compare strings containing any size of number and is heavily tested with a custom benchmark suite to make sure that it is as fast as possible.

Installation

npm install string-natural-compare --save
# or
yarn add string-natural-compare

Usage

naturalCompare(strA, strB[, options])

  • strA (string)
  • strB (string)
  • options (object) - Optional options object with the following options:
    • caseInsensitive (boolean) - Set to true to compare strings case-insensitively. Default: false.
    • alphabet (string) - A string of characters that define a custom character ordering. Default: undefined.
const naturalCompare = require('string-natural-compare');

// Simple, case-sensitive sorting
const files = ['z1.doc', 'z10.doc', 'z17.doc', 'z2.doc', 'z23.doc', 'z3.doc'];
files.sort(naturalCompare);
// -> ['z1.doc', 'z2.doc', 'z3.doc', 'z10.doc', 'z17.doc', 'z23.doc']


// Case-insensitive sorting
const chars = ['B', 'C', 'a', 'd'];
const naturalCompareCI = (a, b) => naturalCompare(a, b, {caseInsensitive: true});
chars.sort(naturalCompareCI);
// -> ['a', 'B', 'C', 'd']

// Note:
['a', 'A'].sort(naturalCompareCI); // -> ['a', 'A']
['A', 'a'].sort(naturalCompareCI); // -> ['A', 'a']


// Compare strings containing large numbers
naturalCompare(
  '1165874568735487968325787328996865',
  '265812277985321589735871687040841'
);
// -> 1
// (Other inputs with the same ordering as this example may yield a different number > 0)


// Sorting an array of objects
const hotelRooms = [
  {street: '350 5th Ave', room: 'A-1021'},
  {street: '350 5th Ave', room: 'A-21046-b'}
];
// Sort by street (case-insensitive), then by room (case-sensitive)
hotelRooms.sort((a, b) => (
  naturalCompare(a.street, b.street, {caseInsensitive: true}) ||
  naturalCompare(a.room, b.room)
));


// When text transformation is needed or when doing a case-insensitive sort on a
// large array of objects, it is best for performance to pre-compute the
// transformed text and store it on the object. This way, the text will not need
// to be transformed for every comparison while sorting.
const cars = [
  {make: 'Audi', model: 'R8'},
  {make: 'Porsche', model: '911 Turbo S'}
];
// Sort by make, then by model (both case-insensitive)
for (const car of cars) {
  car.sortKey = (car.make + ' ' + car.model).toLowerCase();
}
cars.sort((a, b) => naturalCompare(a.sortKey, b.sortKey));


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

Note: Putting numbers in the custom alphabet can cause undefined behaviour.

eslint-plugin-flowtypeeasy-select-rngardenplacemetropoliprettier-plugin-group-importsreact-native-shekhar-bridge-test@oiti/documentoscopy-react-nativequoc-test@vinvc/antd-plugins@infinitebrahmanuniverse/nolb-string-@mediatool/mt-mediaplanning-uiluminos-ui-coresklif-ui-kitsklif-api@everything-registry/sub-chunk-2836jawwy-sdkjawwy_gamification_releasereact-native-sphereuisphereuijawwy_libraryreact-native-credit-card-pkgp149-tablesklif-uireact-native-jawwy_samplelist.jslist.js-fixedkhaled-salem-custom-componentskoa-browsekoa-browse-sevenzipkomodo-sdkkst_list.jslcp-code-generatorjoplin-plugin-copytagsjoplin-plugin-notelistpreviewjoplin-plugin-note-overviewjordy-frijters-test-libnka-gantt-task-reactnocode-generate-pluginmigrator-jsmicroend-componentjulien-easy-modaljrennsoh88-react-native-scroll-indicatornative-date-picker-modulenative-modal-damage-vehiclemy-library-buttonnew-awesome-4321lowcode-plugin-code-generator-ccslowcode-plugin-code-generator-hbclowcode-solution-gate-lowcode-output-plugin-1mavectrajawwy_library_newjawy_library_v1gamification-jawwy-libraryframework_test_library_sixdee_new_jawwyencorecustomlisteslint-plugin-templewallet-testeslint-plugin-flowtype-esmeslint-plugin-ft-flowepro-plugin-code-generatorflipper-pluginflipper-testfluent.adflow.reactnativesdkfluent.adflow.reactnativesdk-alphagaurav-react-native-loopgt-makergriffin-ui-libraryhalifierfeathers-vue-rxflipper-plugin-corefawaterak-online-paymentfawatrak-online-paymentframework_test_library_sixdeeframework_test_library_sixdee_newframework_test_library_sixdee_new_newgenz-native-elementsexpo-renavigateeslint-plugin-amofmslgamification-integration-newpolysortpro-arrayreact-native-app-bubblereact-native-app-integrity-checksumreact-native-azure-communication-servicesreact-native-basic-appreact-native-basic-screenreact-native-auth-service-clientreact-native-aventonfacetec-aventonreact-native-awesome-android-123react-native-awesome-android-123-zeotapreact-native-awesome-module-latestreact-native-awesome-module-tworeact-native-animate-textreact-native-android-video-player-viewreact-native-bleccs-componentsreact-native-dimensions-layoutreact-native-bridge-packagereact-native-bluetooth-device-detectreact-native-ctp-odpreact-native-fedlight-dsm
3.0.1

4 years ago

3.0.0

4 years ago

2.0.3

5 years ago

2.0.2

7 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.1.1

9 years ago

1.1.0

9 years ago

1.0.0

9 years ago

0.1.0

9 years ago