Angular 5按日期,文本,数字排序

时间:2018-03-14 06:14:18

标签: javascript arrays angular sorting

我已经实现了可重复使用的排序功能,按数字排序和文本工作正常,但它无法按日期排序。

orderBy(array: Array<any>, fieldName: string, direction: string) {
  return array.sort((a, b) => {
    let objectA: number|string = '';
    let objectB: number|string = '';
    [objectA, objectB] = [a[fieldName], b[fieldName]];
    let valueA = isNaN(+objectA) ? objectA.toString().toUpperCase() : +objectA;
    let valueB = isNaN(+objectB) ? objectB.toString().toUpperCase() : +objectB;
    return (valueA < valueB ? -1 : 1) * (direction == 'asc' ? 1 : -1);
  });
}

如何按日期,文本编号和特殊字符排序。

3 个答案:

答案 0 :(得分:1)

试试这个:

orderBy(array: Array<any>, fieldName: string, direction: string) {
  return array.sort((a, b) => {
    let objectA: number|string|Date = '';
    let objectB: number|string|Date = '';
    [objectA, objectB] = [a[fieldName], b[fieldName]];

    // I assume that objectA and objectB are of the same type
    return typeof objectA === 'string' ? objectA.localeCompare(objectB) : objectA - objectB;
  });
}

如果无法识别Date类型,您可能需要向es6添加compilerOptions条目,有关详细信息,请参阅this answer

<强>更新

如果您要排序的所有值都是字符串,请尝试:

orderBy(array: Array<any>, fieldName: string, direction: string) {
  return array.sort((a, b) => {
    let objectA: number|string|Date = '';
    let objectB: number|string|Date = '';
    // map function here will convert '15/12/2018' into '2018/12/15'
    // so we can compare values as strings, numbers and strings
    // will remain unchanged
    [objectA, objectB] = [a[fieldName], b[fieldName]].map(i => i.split('/').reverse().join('/'));

    return isNaN(+objectA) ? objectA.localeCompare(objectB) : +objectA - +objectB;
  });
}

答案 1 :(得分:0)

我认为这是最好的选择,因为 localCompare函数 在after之后返回正数,在before之前返回负数,而在等于时返回0 (在此示例中我正在比较.name wich是this.array中的对象 a b 的一个属性)

{{1}}

答案 2 :(得分:-1)

如果你使用的是类型脚本而不是你可以这样做,还没试过,但你可以尝试

public orderby(fieldName : string)
{
    switch (typeof obj[fieldName].constructor.name) {           
            case "String":
                array.sort();
            case "Number":
                  array.sort(function(a,b){
                       return a-b);
                 });
            case "Date"://you can check type and add accordingly 
            //as suggested by @Andriy  its going to be object 
                 array.sort(function(a,b){
                       return new Date(b.date) - new Date(a.date);
                 });
            default:
                throw new Error("Type of T is not a valid return type!");
        }
    } else {
        throw new Error("Key '" + key + "' does not exist!");
    }
}

对于日期排序我喜欢这样,在date中转换值并获得minus操作的值,返回零,加或负值

array.sort(function(a,b){
  return new Date(b.date) - new Date(a.date);
});