https://github.com/interactivethings/d3-comparator
Multi-dimensional comparator function generator for D3
https://github.com/interactivethings/d3-comparator
Last synced: 6 months ago
JSON representation
Multi-dimensional comparator function generator for D3
- Host: GitHub
- URL: https://github.com/interactivethings/d3-comparator
- Owner: interactivethings
- License: bsd-3-clause
- Created: 2013-04-29T20:19:02.000Z (about 12 years ago)
- Default Branch: master
- Last Pushed: 2013-05-30T16:35:04.000Z (almost 12 years ago)
- Last Synced: 2024-11-10T05:37:02.669Z (6 months ago)
- Language: JavaScript
- Size: 116 KB
- Stars: 28
- Watchers: 7
- Forks: 5
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# d3.comparator
A [D3](http://d3js.org) generator for comparator functions. It can be used to easily sort arrays of objects by one or multiple dimensions.
If you want to sort by a single dimension, you end up writing comparators like `function cmp(a, b) { return a.value - b.value; }` or `function cmp(a, b) { return d3.ascending(a.value, b.value); }`. For sorting by two or more dimensions it gets ugly pretty fast. d3.comparator provides a simple API for generating those comparators.
## API
d3.comparator()
Constructs a new comparator with the default return value 0. I.e. using it will not change sort order.
comparator(a, b)
The comparator can be used with the array sort method.
comparator.order(cmp, [accessor])
Adds a dimension to the comparator. The return value of accessor will be compared with cmp (which has to be a comparator function itself, e.g. d3.ascending). If accessor isn't specified, an identity function `function(d) { return d; }` is used.
Dimensions are compared in order. As soon as cmp returns something other than `0`, subsequent dimensions are ignored.
Example using a single dimension:
```javascript
var cmp = d3.comparator().order(d3.ascending, function(d) { return d.value; });
```Example using two dimensions, roughly equivalent to SQL `ORDER BY year DESC, value ASC`:
```javascript
var cmp = d3.comparator()
.order(d3.descending, function(d) { return d.year; })
.order(d3.ascending, function(d) { return d.value; });
```Note: These are just comparator functions. To acually sort an array use
```javascript
someArray.sort(cmp);
```## Author
Jeremy Stucki, [Interactive Things](http://interactivethings.com)
## License
BSD, see LICENSE.txt