Angular 5按日期,文本,数字排序 [英] Angular 5 Sort by date, text, numbers

查看:137
本文介绍了Angular 5按日期,文本,数字排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了可重用的排序功能,按数字和文本排序工作正常,但是按日期排序失败.

I have implemented reusable sorting function,sorting by number and text are working fine,But it fails for sort by date.

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

如何按日期,文本数字和特殊字符排序.

how to sort by date, text numbers and special char.

推荐答案

尝试一下:

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类型,则可能需要在compilerOptions中添加es6条目,请参见

if Date type is not recognized, you may need to add es6 entry to your compilerOptions, see this answer for more details

更新

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

If all your values to be sorted are strings try this:

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

这篇关于Angular 5按日期,文本,数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆