@depax/sort
v1.0.4
Published
Provides a means to sort an array or object be a value of a given key.
Downloads
4
Readme
Sorting
Installation
import sort from "@depax/sort";
const data = [{
value: "hello", weight: 10
}, {
value: "world", weight: -10
}, {
value: "foo"
}];
sort(data, "weight");
This will sort the array like;
[{
value: "world", weight: -10
}, {
value: "foo"
}, {
value: "hello", weight: 10
}]
This can also be reveresed like;
sort(data, "weight", true);
and would return;
[{
value: "hello", weight: 10
}, {
value: "foo"
}, {
value: "world", weight: -10
}]
You can also use function's to return the key weight value, for example;
[{
value: "hello", weight: () => 10
}, {
value: "world", weight: -10
}, {
value: "foo"
}]
You can also sort object's like;
const data = {
world: "world",
hello: { weight: -1 },
foo: "bar",
bar: { weight: 1 }
}
sort(data, "weight");
and this will return;
{
hello: { weight: -1 },
world: "world",
foo: "bar",
bar: { weight: 1 }
}
Array and Object
There is an attach function which will attach the sortByKey functions to the Array and Object classes. And this is done by calling;
import { attach } from "@depax/sort";
attach();
Then the sortByKey functions can be access like;
// Array.
Array.sortByKey(data, "weight");
// - or -
data.sortByKey("weight");
// Object.
Object.sortByKey(data, "weight");
// - or -
data.sortByKey("weight");
Clone and sort
There is also a method to clone and sort an Object or Array;
import { CloneAndSort } from "@depax/sort";
// Sort by weight;
let result = CloneAndSort(data, "weight");
// Reverse sort by weight;
result = CloneAndSort(data, "weight", true);
The methods are also attachable to the Object and Array objects;
let result = data.cloneAndSort("weight");
// Reverse.
result = data.cloneAndSort("weight", true);