首页 > 解决方案 > 如何避免重复命令两次

问题描述

我有一个按值对 JS 对象数组进行排序的函数。该函数需要一个用于进行排序的键。一旦它具有所有值,该函数以 asc 或 desc 顺序对结果进行排序,这就是我使用重复代码的地方。唯一的区别是 ">、<" 符号。

这是代码......,我怎样才能重写它以保持干净而不重复代码?

重复命令: results[0].sort( (a, b) => ( a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 )

      if( this.orderBy ) {
        results = this.order === 'asc' ? 
        results[0].sort( (a, b) => ( 
          a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 ):
        results[0].sort( (a, b) => ( 
          a[ this.orderBy ] < b[ this.orderBy ] ) ? 1 : -1 );
      } 

标签: javascriptarrays

解决方案


这是一种方法:

const inversionFactor = this.order === 'asc' ? 1 : -1;

results = results[0].sort( (a, b) =>
    a[ this.orderBy ] < b[ this.orderBy ] : -1 * inversionFactor : 1 * inversionFactor
);

编辑: 您当前的方法存在一个问题,即您没有考虑两个值相等的情况。这是一种考虑到这一点并避免重复的方法。

// this is a reusable function and can go outside of other functions
const compareBy = (prop, invert) => (a, b) => {
    if (a[prop] === b[prop]) { return 0; } 
    return (a[prop] < b[prop] ? -1 : 1) * (invert ? -1 : 1);
};

results = results[0].sort(compareBy(this.orderBy, this.order === 'desc'));

推荐阅读