精华内容
下载资源
问答
  • 2018-12-11 15:13:00

    前端开发过程中有时需自己手写排序方法

    一般想到数字的字符串排序方法 我们会用到 var newArr = arr. sort(function(a,b){return a - b})来进行排序

    但除此之外我们会需要进行一些字符串的排序 

    此时我们可以用到 var newArr = arr.sort(function(a,b){return a.localeCompare(b)})来进行排序

    但中文排序时发现不是我们想要的  可以通过加参数的方法  a.localeCompare(b,'zh-CN')这样就ojbk了

    转载于:https://www.cnblogs.com/huqi92/p/10102359.html

    更多相关内容
  • js实现字符串排序

    千次阅读 2021-03-06 11:44:56
    规则: 规则 1 :英文字母从 A 到 Z 排列,不区分大小写。 如,输入: Type 输出: epTy 规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。... //字符串切分为数组 let s=line.split("");

    规则:

    规则 1 :英文字母从 A 到 Z 排列,不区分大小写。
    如,输入: Type 输出: epTy
    
    规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。
    如,输入: BabA 输出: aABb
    
    规则 3 :非英文字母的其它字符保持原来的位置。
    如,输入: By?e 输出: Be?y
    
    注意有多组测试数据,即输入有多行,每一行单独处理(换行符隔开的表示不同行)
    
    while(line=readline()){
    	//字符串切分为数组
        let s=line.split("");
        let box = [];
            //symbols数组非字母:每一项元素是数组,由索引和索引所在的数据组成
            let symbols = [];
            for (let i = 0; i < 26; i++) {
                box[i] = "";
            }
            //box数组收集26个数据:每一个数据是字母或字母大小写的组合串或空串(初始化没有值)
            for (let i = 0; i < s.length; i++) {
                let code = s[i].charCodeAt();
                
                if (code >= 97 && code < 123) {//小写字母:97-122
                    box[code - 97] += s[i];           
                } else if (code >= 65 && code < 91) {//大写字母65-90
                    box[code - 65] += s[i];
                } else {//非字母
                    symbols.push([i, s[i]]);
                }
            }
     
            //console.log(box);
            //["AaaAA", "b", "c", "d", "", "F", "gg", "hh", "ii", "", "", "", "mM",
            //"nNn", "oooo", "", "", "", "sS", "tt", "uuu", "", "", "", "y", ""]
            //console.log(symbols);
     
            let res = "";
            box.forEach(item => {
                res += item;
            })
            //console.log(res); 输出 :AaaAAbcdFgghhiimMnNnoooosSttuuuy
    		
    		//item[0]:特殊字符所在的索引
    		//item[1]:特殊字符的值
            symbols.forEach(item => {
                res = res.slice(0, item[0]) + item[1] + res.slice(item[0]);
            })
            console.log(res);
    }
    
    展开全文
  • 本文实例讲述了JS实现为排序好的字符串找出重复行的方法。分享给大家供大家参考,具体如下: 实现这样一个需求,在一个Editplus文档中,有很多行10位的数字,这些数字已经排好序了。 比如: 1234567890 1234567891 ...
  • 字符串排序方法

    2012-08-03 10:33:09
    字符串排序方法 javaScript中的字符串排序。
  • 我的思路是把那几个给定的6个字母分别等效成0-5的数字,然后把那7个字符串中的字母替换成0-5中的数字,再用sort方法进行排序,代码如下: 代码如下: var word = [‘aiye’,’oeu’,’ayo’,’eoyiu’,’yuo’,’you...
  • 为普通数组和对象数组排序,对象数组排序时,可指定排序所依据的对象属性,汉字将以汉语拼音为序。
  • 要转化的键值对字符 var respDesc=“cardid=64157001&cardnum=1&sporder_id...以上这篇js将键值对字符串转为json字符串方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。
  • 如何在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
    
    展开全文
  • js 字符串的全排序

    千次阅读 2020-04-27 14:24:04
    实现全排序 function fullpermutate(str) { var result = []; if (str.length > 1) { //遍历每一项 for (var m = 0; m < str.length; m++) { //拿到当前的元素 var left = str[m]; //除当前元素的其他...
  • JS更符合实际的字符串排序【字母顺序+数字大小排序】
  • js实现字符串的排列

    2022-03-21 00:04:03
    方法一 const res = [], temp = [] const len = str.length const arr = str.split('') var help = function() { if (temp.length === len) { res.push(temp.join('')) return } for (const s of arr) { ...
  • localeCompare()方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。 语法:str.localeCompare(compareStr) 当 引用字符串 在 比较字符串 前面时返回 -1 当 引用字符串 在 比较...
  • JavaScript字符串内置方法方法 描述 charAt() 它返回指定索引处的字符(位置) charCodeAt() 它返回指定索引处字符的Unicode codePointAt() codePointAt()方法返回一个非负整数,它是Unicode代码点...
  • 实现了字符串、数字并存时,字符串排在数字之后,数字以数值大小进行排序
  • javascript字符串排序

    2011-09-01 17:40:51
    这是一个JAVASCRIPT字符串排序方法,比默认的SORT方法效率要高,速度快。
  • 默认sort方法是按照字符进行排序 此时sort方法没有加参数 4、es5的严格模式和宽松模式区别 ES5严格模式是限制性更强的JavaScript变体,它与常规JavaScript的语义不同,其分析更为严格。就是在js代码最前面或者...
  • 希望得到的排序结果是 abc2,abc11,abc123 就是先按照字符串排字符或文字,然后按照数字排 解决方案: var list = ['abc123', 'abc11', 'abc2'] var list2 = [] list2 = list.sort(function(a, b) { return a....
  • Hash 可以看作是一个 关联数组,它对每一个值都绑定了一个唯一的键(值并不必须是唯一的), 然而,它不能保证迭代时元素的...因为 JavaScript 程序语言的特性,每个对象实际上都是一个 hash,下面我们就来详细探讨下。
  • Js里如何实现对字符串类型的数组、数字类型数组以及对象类型数组的排序呢?废话不多说,上码! 1、普通数组的排序(数字) 2、普通数组的排序(字符串) 3、普通数组的排序(对象)
  • js实现数组中的字符串按长度排序,长度一样按字母顺序排序
  • 在上篇文章给大家介绍了JavaScript sort数组排序方法和自我实现排序方法小结,用自己的方法实现了数字数组的排序。 当然,实际运用中,我还是会使用sort方法更加方便.但是,我上一篇博文,仅仅是实现了数字排序,而srot...
  • 中英文数字混合字符串排序js

    千次阅读 2021-09-26 17:05:19
    一、思路 两两比较,根据优先级交换位置。比较的时候,一个字符一...同时字符串长度长的优先级低 二、 要排序的数据 data:[{'name':'分组2'},{'name':'分组45'},{'name':'分组4'},{'name':'fusa'},{'name':'4647'},]
  • 本文实例讲述了JS实现快速比较两个字符串中包含有相同数字的方法。分享给大家供大家参考,具体如下: 有两个字符串: $a = 5,8,0; $b = 8,0,5; 怎样快速比较这两个字符串包含的数字是相同的,其中分隔符都是相同的...
  • js实现数组的多条件排序 其实这种排序在后台做一个order by 啥的就解决了 但是前端做也是可以的. 需求是这样的 例如有这样一个数组给你排序 const jsonStudents = [ {name:"张三", totalScore:"...
  • 字符串排序-C语言实例

    千次阅读 2020-05-02 13:23:15
    1、简单的字符串排序 给定有限个字符串,将其按照大小顺序排列。此时的大小顺序简单来说我们可以先认为是ASCLL码的大小顺序。由此我们只需要比较字符串的ASCLL码的大小即可。 2、算法设计 1、输入10个字符串; 2、...
  • Java更好的字符串排序(字母顺序+数字大小排序)

    千次阅读 热门讨论 2021-11-13 13:22:15
    按照java自带的字符串排序,是按照每一个字母的ASCII码顺序进行排序,代码如下: List<String> strList = Arrays.asList(new String[]{"5栋", "7栋", "4栋", "15栋", "24栋", "涉外国际7栋", "涉外国际6栋", ...
  • JS字符串排序

    2015-12-13 11:45:00
    function quick_sort(arr) { var arry1, arry2, mid; if (arr.length < 2) return arr; else if (arr.length == 2) ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 111,116
精华内容 44,446
关键字:

js字符串排序方法