2023-05-10

Javascript :: Sort array of objects / Custom sorting

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(itemAitemB) {
  if (
itemA itemBreturn 1;
  if (itemA itemBreturn -1;
  return 0; // if it's not one of the above, they're the same
}

  • for objects:

function compareItems(itemAitemB) {
  if (
itemA.numberVal itemB
.numberValreturn 1;
  if (itemA.numberVal itemB.numberValreturn -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(itemAitemB) {
  if (
itemA itemB) return 1;
  if (itemA itemBreturn -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 = [3241];
myArray.sort(function compareItems(itemAitemB) {
  if (itemA itemBreturn 1;
  if (itemA itemBreturn -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 = [3241];
myArray.sort((itemAitemB) => {
  if (itemA itemBreturn 1;
  if (itemA itemBreturn -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...

Javascript :: comparison operators, using == vs === and != vs !==

Comparison operators are distinguished following simple logic, whether data type is being included or not. Essentially if it is === or !==, ...