精华内容
下载资源
问答
  • 2019-09-27 18:13:43

    js 给时间或中文汉字排序

    eg: 对数据早餐,晚餐,中餐,按早中晚的顺序排序

    1.已知时间,比较时间大小。

    2.未知时间,直接排序汉字

     let dataList1=[{name:'早餐',mealStartTime:'8:30:00'},{name:'晚餐',mealStartTime:'18:30:00'},{name:'午餐',mealStartTime:'12:30:00'}]
    
     let dataList2=['晚餐','早餐','午餐']
    
    
    
     let list =that.compareConsumeType(dataList,'mealStartTime')
     let arr =that.compareConsumeType(dataList2,' ')
    
    
    //将时分秒转为时间戳 将18:30:30 转时间戳
        time_to_sec(time) {
          if (time !== null) {
              var s = "";
              var hour = time.split(":")[0];
              var min = time.split(":")[1];
              var sec = time.split(":")[2];
              s = Number(hour * 3600) + Number(min * 60) + Number(sec);
              return s;
          }
        },
    
    
    //将餐别按早午晚顺序排序,name(早午晚对应的时间)存在时
        compareConsumeType(arr,name){
          if(name){
            arr.sort((a,b)=>{
               return common.time_to_sec(a[name])-common.time_to_sec(b[name])
            })
          }else{
            arr.sort((a,b)=>{  //中文字符排序 ,早餐-午餐-晚餐
               return b.localeCompare(a,'zh-CN')
            })
          }
          
           return arr
          
        },

    更多相关内容
  • 如何在JavaScript中对字符串排序

    千次阅读 2020-06-29 11:07:35
    I have a list of objects I wish to sort based on a field attr of type string. 我有一个对象列表,希望根据字符串类型的字段

    本文翻译自:How to sort strings in JavaScript

    I have a list of objects I wish to sort based on a field attr of type string. 我有一个对象列表,希望根据字符串类型的字段attr进行排序。 I tried using - 我尝试使用-

    list.sort(function (a, b) {
        return a.attr - b.attr
    })
    

    but found that - doesn't appear to work with strings in JavaScript. 但发现-在JavaScript中似乎不适用于字符串。 How can I sort a list of objects based on an attribute with type string? 如何根据具有字符串类型的属性对对象列表进行排序?


    #1楼

    参考:https://stackoom.com/question/DJF/如何在JavaScript中对字符串排序


    #2楼

    I had been bothered about this for long, so I finally researched this and give you this long winded reason for why things are the way they are. 我已经为此烦恼了很长时间,所以我终于对此进行了研究,并为您提供了如此漫长的原因来说明事情的现状。

    From the spec : 规格

    Section 11.9.4   The Strict Equals Operator ( === )
    
    The production EqualityExpression : EqualityExpression === RelationalExpression
    is evaluated as follows: 
    - Let lref be the result of evaluating EqualityExpression.
    - Let lval be GetValue(lref).
    - Let rref be the result of evaluating RelationalExpression.
    - Let rval be GetValue(rref).
    - Return the result of performing the strict equality comparison 
      rval === lval. (See 11.9.6)
    

    So now we go to 11.9.6 所以现在我们去11.9.6

    11.9.6   The Strict Equality Comparison Algorithm
    
    The comparison x === y, where x and y are values, produces true or false. 
    Such a comparison is performed as follows: 
    - If Type(x) is different from Type(y), return false.
    - If Type(x) is Undefined, return true.
    - If Type(x) is Null, return true.
    - If Type(x) is Number, then
    ...
    - If Type(x) is String, then return true if x and y are exactly the 
      same sequence of characters (same length and same characters in 
      corresponding positions); otherwise, return false.
    

    That's it. 而已。 The triple equals operator applied to strings returns true iff the arguments are exactly the same strings (same length and same characters in corresponding positions). 如果参数是完全相同的字符串(在相应位置具有相同的长度和相同的字符),则应用于字符串的三元等于运算符将返回true。

    So === will work in the cases when we're trying to compare strings which might have arrived from different sources, but which we know will eventually have the same values - a common enough scenario for inline strings in our code. 因此,当我们尝试比较可能来自不同来源的字符串,但我们知道它们最终将具有相同的值时, ===将起作用。这是我们代码中内联字符串足够普遍的情况。 For example, if we have a variable named connection_state , and we wish to know which one of the following states ['connecting', 'connected', 'disconnecting', 'disconnected'] is it in right now, we can directly use the === . 例如,如果我们有一个名为connection_state的变量,并且我们想知道现在处于以下哪个状态['connecting', 'connected', 'disconnecting', 'disconnected'] ,我们可以直接使用===

    But there's more. 但是还有更多。 Just above 11.9.4, there is a short note: 在11.9.4之上,有一个简短的注释:

    NOTE 4     
      Comparison of Strings uses a simple equality test on sequences of code 
      unit values. There is no attempt to use the more complex, semantically oriented
      definitions of character or string equality and collating order defined in the 
      Unicode specification. Therefore Strings values that are canonically equal
      according to the Unicode standard could test as unequal. In effect this 
      algorithm assumes that both Strings are already in normalized form.
    

    Hmm. What now? 现在怎么办? Externally obtained strings can, and most likely will, be weird unicodey, and our gentle === won't do them justice. 外部获得的字符串可能而且很可能是奇怪的单一代码,而我们温和的===不会使它们公正。 In comes localeCompare to the rescue: 在谈到localeCompare救援:

    15.5.4.9   String.prototype.localeCompare (that)
        ...
        The actual return values are implementation-defined to permit implementers 
        to encode additional information in the value, but the function is required 
        to define a total ordering on all Strings and to return 0 when comparing
        Strings that are considered canonically equivalent by the Unicode standard. 
    

    We can go home now. 我们现在可以回家了。

    tl;dr; tl; dr;

    To compare strings in javascript, use localeCompare ; 要比较javascript中的字符串,请使用localeCompare if you know that the strings have no non-ASCII components because they are, for example, internal program constants, then === also works. 如果您知道字符串没有非ASCII成分,因为它们是例如内部程序常量,则===也可以。


    #3楼

    In your operation in your initial question, you are performing the following operation: 在初始问题中的操作中,您正在执行以下操作:

    item1.attr - item2.attr
    

    So, assuming those are numbers (ie item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. 因此,假设这些是数字(即item1.attr =“ 1”,item2.attr =“ 2”),只要确保输入类型,您仍然可以使用“ ===”运算符(或其他严格的求值器)。 The following should work: 以下应该工作:

    return parseInt(item1.attr) - parseInt(item2.attr);
    

    If they are alphaNumeric, then do use localCompare(). 如果它们是alphaNumeric,则请使用localCompare()。


    #4楼

    An updated answer (October 2014) 更新的答案(2014年10月)

    I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. 我对这种字符串自然排序顺序感到非常恼火,因此花了很多时间来研究这个问题。 I hope this helps. 我希望这有帮助。

    Long story short 长话短说

    localeCompare() character support is badass, just use it. localeCompare()字符支持很糟糕,只需使用它即可。 As pointed out by Shog9 , the answer to your question is: 正如Shog9指出的Shog9 ,您的问题的答案是:

    return item1.attr.localeCompare(item2.attr);
    

    Bugs found in all the custom javascript "natural string sort order" implementations 在所有自定义javascript“自然字符串排序顺序”实现中发现的错误

    There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order" 有很多自定义实现,试图更精确地进行字符串比较,称为“自然字符串排序顺序”

    When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases). 当“尝试”这些实现时,我总是注意到一些奇怪的“自然排序顺序”选择,或者是错误(或者在最佳情况下是遗漏)。

    Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly. 通常,特殊字符(空格,破折号,“&”号,方括号等)未正确处理。

    You will then find them appearing mixed up in different places, typically that could be: 然后,您会发现它们在不同的位置混合出现,通常可能是:

    • some will be between the uppercase 'Z' and the lowercase 'a' 有些会在大写字母“ Z”和小写字母“ a”之间
    • some will be between the '9' and the uppercase 'A' 有些会在'9'和大写字母'A'之间
    • some will be after lowercase 'z' 有些将在小写字母“ z”之后

    When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). 当一个人希望所有特殊字符都被“分组”在一个地方时,除了空格特殊字符(总是第一个字符)。 That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters. 也就是说,要么全部在数字之前,要么全部在数字和字母之间(小写字母和大写字母彼此“在一起”),或者全部在字母之后。

    My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on). 我的结论是,当我开始添加几乎不寻常的字符(即带有变音符号或字符(例如破折号,感叹号等)的字符时,它们都无法提供一致的顺序。

    Research on the custom implementations: 有关自定义实现的研究:

    Browsers' native "natural string sort order" implementations via localeCompare() 浏览器通过localeCompare()的本机“自然字符串排序顺序”实现

    localeCompare() oldest implementation (without the locales and options arguments) is supported by IE6+, see http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx (scroll down to localeCompare() method). IE6 +支持最旧的localeCompare()实现(没有语言环境和选项参数),请参见http://msdn.microsoft.com/zh-cn/library/ie/s4esdbwz(v = vs.94).aspx (向下滚动)到localeCompare()方法)。 The built-in localeCompare() method does a much better job at sorting, even international & special characters. 内置的localeCompare()方法在排序(甚至国际字符和特殊字符localeCompare()方面做得更好。 The only problem using the localeCompare() method is that "the locale and sort order used are entirely implementation dependent". 使用localeCompare()方法的唯一问题是“使用的语言环境和排序顺序完全取决于实现”。 In other words, when using localeCompare such as stringOne.localeCompare(stringTwo): Firefox, Safari, Chrome & IE have a different sort order for Strings. 换句话说,当使用诸如stringOne.localeCompare(stringTwo)之类的localeCompare时:Firefox,Safari,Chrome和IE对字符串的排序顺序不同。

    Research on the browser-native implementations: 对浏览器本地实现的研究:

    Difficulty of "string natural sorting order" “字符串自然排序顺序”的困难

    Implementing a solid algorithm (meaning: consistent but also covering a wide range of characters) is a very tough task. 实施可靠的算法(意味着:一致但也涵盖了广泛的字符)是一项艰巨的任务。 UTF8 contains more than 2000 characters & covers more than 120 scripts (languages) . UTF8包含2000多个字符涵盖120多个脚本(语言) Finally, there are some specification for this tasks, it is called the "Unicode Collation Algorithm", which can be found at http://www.unicode.org/reports/tr10/ . 最后,有一些针对此任务的规范,称为“ Unicode排序算法”,可以在http://www.unicode.org/reports/tr10/上找到。 You can find more information about this on this question I posted https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order 您可以在我发布的这个问题上找到有关此问题的更多信息https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order

    Final conclusion 定论

    So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). 因此,考虑到我遇到的javascript自定义实现所提供的当前支持水平,我们可能永远不会看到有什么东西能够接近支持所有这些字符和脚本(语言)的。 Hence I would rather use the browsers' native localeCompare() method. 因此,我宁愿使用浏览器的本地localeCompare()方法。 Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders. 是的,它确实存在跨浏览器不一致的缺点,但是基本测试表明,它涵盖了更大范围的字符,允许可靠且有意义的排序顺序。

    So as pointed out by Shog9 , the answer to your question is: 因此,正如Shog9所指出的,您的问题的答案是:

    return item1.attr.localeCompare(item2.attr);
    

    Further reading: 进一步阅读:

    Thanks to Shog9's nice answer, which put me in the "right" direction I believe 多亏Shog9的好回答,我相信我朝着“正确”的方向前进


    #5楼

    list.sort(function(item1, item2){
        return +(item1.attr > item2.attr) || +(item1.attr === item2.attr) - 1;
    }) 
    

    How they work samples: 它们是如何工作的:

    +('aaa'>'bbb')||+('aaa'==='bbb')-1
    +(false)||+(false)-1
    0||0-1
    -1
    
    +('bbb'>'aaa')||+('bbb'==='aaa')-1
    +(true)||+(false)-1
    1||0-1
    1
    
    +('aaa'>'aaa')||+('aaa'==='aaa')-1
    +(false)||+(true)-1
    0||1-1
    0
    

    #6楼

    Answer (in Modern ECMAScript) 答案(现代ECMAScript中)

    list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))
    

    Or 要么

    list.sort((a, b) => +(a.attr > b.attr) || -(a.attr < b.attr))
    

    Description 描述

    Casting a boolean value to a number yields the following: 将布尔值转换为数字会产生以下结果:

    • true -> 1 true -> 1
    • false -> 0 false -> 0

    Consider three possible patterns: 考虑三种可能的模式:

    • x is larger than y: (x > y) - (y < x) -> 1 - 0 -> 1 x大于y: (x > y) - (y < x) -> 1 - 0 > 1
    • x is equal to y: (x > y) - (y < x) -> 0 - 0 -> 0 x等于y: (x > y) - (y < x) -> 0 - 0 > 0
    • x is smaller than y: (x > y) - (y < x) -> 0 - 1 -> -1 x小于y: (x > y) - (y < x) -> 0 - 1 > -1

    (Alternative) (可选)

    • x is larger than y: +(x > y) || -(x < y) x大于y: +(x > y) || -(x < y) +(x > y) || -(x < y) -> 1 || 0 +(x > y) || -(x < y) -> 1 || 0 1 || 0 -> 1 1 || 0 > 1
    • x is equal to y: +(x > y) || -(x < y) x等于y: +(x > y) || -(x < y) +(x > y) || -(x < y) -> 0 || 0 +(x > y) || -(x < y) -> 0 || 0 0 || 0 -> 0 0 || 0 > 0
    • x is smaller than y: +(x > y) || -(x < y) x小于y: +(x > y) || -(x < y) +(x > y) || -(x < y) -> 0 || -1 +(x > y) || -(x < y) -> 0 || -1 0 || -1 -> -1 0 || -1 > -1

    So these logics are equivalent to typical sort comparator functions. 因此,这些逻辑等效于典型的排序比较器功能。

    if (x == y) {
        return 0;
    }
    return x > y ? 1 : -1;
    
    展开全文
  • 字符串排序

    需求: 需要按照 ASCII 码的顺序对字符串进行排序,如 [“abc”,“a”,“b”,“c”,“bc”],按照 ASCII 码排序应该为[ “a”, “abc”, “b”, “bc”, “c”]。

    方法一: 可以通过 sort 方法进行排序

    let arr = ["abc","a","b","c","bc"];
    let res = arr.sort();
    console.log(res) // [ "a", "abc", "b", "bc", "c"]
    

    sort方法是 js 数组的一个方法,可以对数组进行排序,它接收一个函数作为参数,该函数有两个参数,可以自定义条件进行排序;例如以下代码就是根据字符串长度的升序进行排序

    let arr = ["abc","a","b","c","bc"];
    let res = arr.sort((a,b)=>{
    	return a.length-b.length
    });
    console.log(res) // [ "a", "b", "c", "bc", "abc"]
    

    方法二: 如果只是比较两个字符串的 ASCII 排序,也可以使用字符串的 localeCompare 方法,如下:

    let str = "pink";
    console.log(str.localeCompare("black"))   // 1
    console.log(str.localeCompare("pink"))   // 0
    console.log(str.localeCompare("yellow"))   // -1
    
    展开全文
  • 华为机试--字符串排序

    千次阅读 2022-04-24 17:09:50
    输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。 输出描述: 数据输出n行,输出结果为按照字典序排列的字符串。 示例1: 输入:9 cap to cat card ...

    描述:

    给定 n 个字符串,请对 n 个字符串按照字典序排列。

    数据范围: 1≤n≤1000  ,字符串长度满足 1≤len≤100 

    输入描述:

    输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。

    输出描述:

    数据输出n行,输出结果为按照字典序排列的字符串。

    示例1:

    输入:9
    cap
    to
    cat
    card
    two
    too
    up
    boat
    boot
    
    输出:
    boat
    boot
    cap
    card
    cat
    to
    too
    two
    up

    解题思路:

    这道题最麻烦的在于逐个字符根据ASCII码值的排序,一般碰到这种问题,就考虑使用C语言的qsort函数,结合字符串的比较函数strcmp,strcmp函数对两个参数的比较就是逐个字符按照ASCII值来比较的,如下,定义一个回调函数,再使用qsort排序即可。

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define MAX 100
    
    struct keyValue {
        char arr[MAX];
        int len;
    };
    
    // 回调函数--根据ASCII逐个字符比较
    int cmp(const void* a, const void* b) {
        return strcmp((char*)a, (char*)b);
    }
    
    int main() {
        int n, i;
        struct keyValue a[1000];
        scanf("%d\n", &n);
        for (i = 0; i < n; i++) {
            scanf("%[^\n]\n", a[i].arr);
            a[i].len = strlen(a[i].arr);
        }
        qsort(a, n, sizeof(a[0]), cmp);
        for (i = 0; i < n; i++) {
            // 下面这个循环我本来想用printf("%s\n", a[i].arr);但是这种格式控制都只排序了一部分,而且每个字符串后多了一个字符,不知道bug起因,所以改用单个字符循环输出,这样就提高了时间复杂度
            for(int j = 0; j < a[i].len; j++){
                printf("%c", a[i].arr[j]);
            }
            printf("\n");
        }
    
        return 0;
    }
    展开全文
  • 主要的JS代码如下: var tbody = document.querySelector('#tableSort').tBodies[0]; var th = document.querySelector('#tableSort').tHead.rows[0].cells; var td = tbody.rows; for (var i = 0;i < th.length...
  • 根据数组里面的时间字符串排序

    千次阅读 2019-06-03 16:31:15
    大致需求就是,有关时间的内容存储到数组里面的某一项,并且是以字符串的形式展示 var data = [{ "id": "001", "time": "2019-5-28" },{ "id": "002", "time": "2019-5-28" },{ "id": "003", "time": ...
  • var arr= ["2021-03-16 00:00:00", "2021-03-16 23:59:59", "2021-03-16 20:00:00", "2021-03-16 16:00:00", "2021-03-16 12:00:00", "2021-03-16 08:00:00", "2021-03-16 04:00:00"]; arr.sort(function(a, b) {...
  • js日期利用sort排序

    2022-04-18 10:00:58
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>...scrip
  • 今天我们就来看一看在JS中,日期字符串和时间戳之间的相互转换......当拿到后台返回的数据后,会有一个形如: issue_date:20161221 的字段,现在我们需要把它处理成时间戳,思路如下:20161221(数字) -----> ...
  • arr: [ {time: '2021/08/10 20:18'}, {time: '2021/08/10 05:18'}, {time: '2021/07/10 14:18'}, {time: '2021/08/13 14:05'}, {time: '2021/08/01 20:18'}, {time: '2021/09/10 20:18'}, ...
  • sql 将8位字符串转换成日期型 将8位字符串转换成日期型,方法如下: ),) C# 字符串string类型转换成DateTime类型 或者 string转换成DateTime?(字符串转换成可空日期类型) 在c#中,string类型转换成DateTime类型是经常...
  • js 日期排序(Sort)

    万次阅读 2016-07-22 15:34:09
    按创建时间排序 例如 response=data.rows 1.倒序 response.sort(function (a, b) { return a.createtime; }); 2.升序 response.sort(function (a, b) { return a.createtime>b.crea
  • 冒泡排序 1.比较相邻的两个元素,如果前一个比后一个大,则交换位置。...(1)字符串对象 String; (2)日期对象 Date; (3)数组对象 Array; (4)数值对象 Math 和 Number 处理字符串 (1...
  • js日期排序(使用sort)

    千次阅读 2020-05-29 14:30:56
    近期写项目,需要用对象的中一个key来进行排序,发现element框架表格带的排序不太好用,于是自己封装了一个函数,来根据日期进行排序,也可以根据number类型的大小来进行排序 先看按日期排序的函数 let data = [{ ...
  • 字符串时间排序

    2021-12-29 15:49:34
    数据: list: [ { time: "2012/09/10", }, { time: "2023/08/19", }, { time: "2022/08/19", }, { time: "2021/06/22", }, { time: "2069/03/19", }, { time: "2018/02/06", }, ], 排序: this.list.sort((a, b) => { ...
  • js日期进行排序

    2021-10-22 10:50:48
    let data = [ { count:"8", name: "21-09" },{ count:"8", name: "20-11" },{ count:"8", name: "20-12" },{ .
  • 有时候处理数据时,想要按照字符串中的数字的大小进行排序。譬如,存在一组记录文件,分别为‘1.dat’,'2.dat'...当我把该文件夹中的所有记录文件名读到一个列表中,这些字符串的排列方式为:如何让这些字符串按照...
  • js字符串怎么转化为日期

    千次阅读 2018-11-08 23:13:38
    字符串格式为str = "2010-08-01";怎么把它转化为日期,并且在day上面加1,谢谢各位! 我有更好的答案 分享到: 按默认排序|按时间排序 3条回答 2013-12-13 15:24 zhaoapk |十一级 1 2 ...
  • (data,key) => { data.map(item => { item._tm = item[key].replace(/-/g,'') *1 }) return data.sort((a, b) => a._tm - b._tm) } 思路:如 2022-04-16 把字符串中的-去掉再转成数字即可用sort 进行排序
  • const hislist = [{ 'id':'1','date':'2020-11-21'}, { 'id':'2','date':'2020-11-12'}, { 'id':'3','date':'2020-12-24'}, { 'id':'4','date':'2020-11-25'} ...
  • JavaScript 中的所有事物都是对象,如:字符串、数值、数组、函数等,每个对象带有属性和方法。 var objectName =new Array();//使用new关键字定义对象 2.Date日期对象 定义一个时间对象: var Udate=new Date(); ...
  • JavaScript 中的所有事物都是对象:字符串、数字、数组、日期,等等。 在 JavaScript 中,对象是拥有属性和方法的数据。 属性是与对象相关的值。 方法是能够在对象上执行的动作。.关键词() 举例:汽车就是现实生活...
  • 1,字符串对象实例化方法 2,字符串 length 属性 3,字符串 indexOf 方法 使用 indexOf() 来定位字符串中某一个指定的字符首次出现的位置 4,字符串 replace()方法 使用 replace() 方法在字符串中用某些字符替换...
  • } //字符串日期格式,strDate要转为日期格式的字符串 function convertDateFromString(dateString) { if (dateString) { var arr1 = dateString.split(" "); var sdate = arr1[0].split("-"); var date = new ...
  • js数组字符串对象基础知识

    千次阅读 2022-03-25 09:31:43
    自用小技巧 强制转换 Number() 强制转换为数值型 Number('2') //2 Number('2a') //NaN Number(true) //1 Number(undefined)//NaN Number(null) //0 parseInt() 强制转换为整形 ...常用于将小数和字符
  • js字符串比较大小

    千次阅读 2020-07-14 15:43:58
    大于(>), 小于(<)运算符 javascript字符串在进行...2、当日期字符串比较,如果,没有具体时分秒,则转为00:00:00进行比较 console.log('2020-10-10 09:00' > '2020-10-10') //true console.log('2020-10-01'

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 32,895
精华内容 13,158
热门标签
关键字:

js日期字符串排序