Johnny Metz
Johnny Metz

Reputation: 5965

JavaScript: sort array of objects dynamically given array of fields

I'm trying to write a helper function in JavaScript that takes an unsorted array of objects and an array of fields and sorts the array in place based on the given fields. Here's what I have so far:

const sortByFieldsInPlace = (arr, fieldNames) => {
  arr.sort((a, b) => {
    for (const field of fieldNames) {
      if (a[field] > b[field]) return 1;
      if (a[field] < b[field]) return -1;
    }
  });
};

It seems to work so far:

const arr1 = [
  { name: 'A', code: 'D' },
  { name: 'B', code: 'A' },
  { name: 'A', code: 'Z' },
  { name: 'A', code: 'A' },
  { name: 'B', code: 'D' },
  { name: 'B', code: 'B' },
  { name: 'B', code: 'B' }
];
sortByFieldsInPlace(arr1, ['name', 'code'])
console.log(arr1)
// [
//   { name: 'A', code: 'A' },
//   { name: 'A', code: 'D' },
//   { name: 'A', code: 'Z' },
//   { name: 'B', code: 'A' },
//   { name: 'B', code: 'B' },
//   { name: 'B', code: 'B' },
//   { name: 'B', code: 'D' }
// ]

const arr2 = [
  { name: 'A', code: 'D' },
  { name: 'B', code: 'A' },
  { name: 'A', code: 'Z' },
  { name: 'A', code: 'A' },
  { name: 'B', code: 'D' },
  { name: 'B', code: 'B', status: 10 },
  { name: 'B', code: 'B', status: 9 }
];
sortByFieldsInPlace(arr2, ['name', 'code', 'status'])
console.log(arr2)
// [
//   { name: 'A', code: 'A' },
//   { name: 'A', code: 'D' },
//   { name: 'A', code: 'Z' },
//   { name: 'B', code: 'A' },
//   { name: 'B', code: 'B', status: 9 },
//   { name: 'B', code: 'B', status: 10 },
//   { name: 'B', code: 'D' }
// ]

Does this look good or does anyone have a better solution?

Upvotes: 1

Views: 603

Answers (1)

John D
John D

Reputation: 58

Your solution seems good to me, I would add a final "return 0" outside of the for loop to cover the situation where the objects being compared are identical. Other than that I think you have it covered.

Upvotes: 1

Related Questions