A common issue is handling array sorting when unable to test/validate the code as is common with low-code tooling.
To that end, sorting can usually be done by setting a comparison function.
The comparison function takes two values as input and must return a value with the following rules:
input: two values, for the examples below these will be named itemA and itemB
output: a numeric value that when it's 0 no changes for the positions of itemA and itemB in relation to each other, if positive (>0) then itemA will be placed before itemB and if negative, itemB will be placed before itemA.
The items in the parameters can be objects or values, it's a matter of using the relevant fields/members for the object to deliver a return value.
Comparer function examples:
- for values:
function compareItems(itemA, itemB) {
if (itemA > itemB) return 1;
if (itemA < itemB) return -1;
return 0; // if it's not one of the above, they're the same
}
- for objects:
function compareItems(itemA, itemB) {
if (itemA.numberVal > itemB.numberVal) return 1;
if (itemA.numberVal < itemB.numberVal) return -1;
return 0; // if it's not one of the above, they're the same
}
Fully working examples below:
- Using a compare function:
function compareItems(itemA, itemB) {
if (itemA > itemB) return 1;
if (itemA < itemB) return -1;
return 0; // if it's not one of the above, they're the same
}
var myArray = [3, 2, 4, 1];
myArray.sort(compareItems);
console.log(JSON.stringify(myArray));
//outputs: [1,2,3,4]
- Using an inline comparison function:
var myArray = [3, 2, 4, 1];
myArray.sort(function compareItems(itemA, itemB) {
if (itemA > itemB) return 1;
if (itemA < itemB) return -1;
return 0; // if it's not one of the above, they're the same
});
console.log(JSON.stringify(myArray));
//outputs: [1,2,3,4]
- Using an inline comparison arrow function:
var myArray = [3, 2, 4, 1];
myArray.sort((itemA, itemB) => {
if (itemA > itemB) return 1;
if (itemA < itemB) return -1;
return 0; // if it's not one of the above, they're the same
});
console.log(JSON.stringify(myArray));
//outputs: [1,2,3,4]
No comments:
Post a Comment
Please provide any feedback or post questions here...