📜  javascript orderby - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:06.414000             🧑  作者: Mango

JavaScript Orderby

When working with data, it is often necessary to sort the data based on certain criteria. In JavaScript, the sort() method can be used to sort arrays, but it can be a bit tricky to use if you need to sort based on multiple criteria or if you need to sort in a specific order. That is where the orderby function comes in handy.

Implementation

Here is a simple implementation of orderby function in JavaScript:

function orderby(arr, props) {
  return arr.sort((a, b) => {
    return props.reduce((p, i) => {
      if (p === 0) {
        const left = (typeof a[i] === 'string') ? a[i].toUpperCase() : a[i];
        const right = (typeof b[i] === 'string') ? b[i].toUpperCase() : b[i];

        if (left < right) {
          return -1;
        } else if (left > right) {
          return 1;
        }
      }

      return p;
    }, 0);
  });
}
Usage

The orderby function takes two parameters:

  • An array arr to be sorted
  • An array props of properties to sort on, in the order of priority.

Here is an example usage:

const persons = [
  { name: 'John Doe', age: 30, gender: 'Male' },
  { name: 'Jane Doe', age: 25, gender: 'Female' },
  { name: 'Bob Smith', age: 18, gender: 'Male' },
  { name: 'Sarah Johnson', age: 40, gender: 'Female' }
];

// sort by age, then by name
orderby(persons, ['age', 'name']);

// sort by gender, then by name
orderby(persons, ['gender', 'name']);

The result will be the sorted array based on the specified properties.

Conclusion

orderby function in JavaScript provides a convenient way to sort arrays based on multiple criteria and in a specific order. It can be useful in various scenarios where data sorting is required.