-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.js
More file actions
29 lines (28 loc) · 770 Bytes
/
array.js
File metadata and controls
29 lines (28 loc) · 770 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
*
* @param {object[]} array
* @param {string} attribute
* @param {boolean} asc
* @param {func} auxFunction
* @returns
*/
const sortBy = (array, attribute = "id", asc = false, auxFunction = null) => {
return array.sort((itemA, itemB) => {
if (auxFunction) {
console.assert(
auxFunction(itemA) !== undefined,
"auxFunction should return something"
);
if (auxFunction(itemA) > auxFunction(itemB)) return !asc ? -1 : 1;
if (auxFunction(itemA) < auxFunction(itemB)) return !asc ? 1 : -1;
return 0;
} else {
if (itemA[attribute] > itemB[attribute]) return !asc ? -1 : 1;
if (itemA[attribute] < itemB[attribute]) return !asc ? 1 : -1;
return 0;
}
});
};
module.exports = {
sortBy,
};