角5按日期排序,文字,数字(Angular 5 Sort by date, text, number

2019-09-29 04:41发布

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

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);
  });
}

如何通过日期,文本数字和特殊字符进行排序。

Answer 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 ,看到这个回答更多细节

UPDATE

如果要排序的所有值都是字符串试试这个:

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;
  });
}


Answer 2:

我认为这可能是最好的,因为localCompare 功能 后返回正面和前底片和0的equals(在这个例子中,我比较.NAME至极的对象AB的属性附加伤害是在this.array)

this.array.sort((a, b) => { 
 return a.name.localeCompare(b.name);
});


Answer 3:

如果您使用的脚本类型比你可以像这样,还没有尝试,但你可以试模

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!");
    }
}

日期排序我喜欢这一点,在日期转换值,并获得返回零减运算值,加上或负vlaue

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


文章来源: Angular 5 Sort by date, text, numbers