如何根据每个元素的长度对数组进行排序?

时间:2022-09-25 08:49:24

I have an array like this:

我有一个像这样的数组:

arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "abcd"

After sorting, the output array should be:

排序后,输出数组应为:

arr[0] = "abcdefgh"
arr[1] = "abcd"
arr[2] = "ab"  

I mean, I want in the descending order of the length of each element.

我的意思是,我希望按每个元素长度的降序排列。

6 个解决方案

#1


149  

You can use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

您可以使用Array.sort方法对数组进行排序。将字符串长度视为排序标准的排序函数可以使用如下:

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});

Note: sorting ["a", "b", "c"] by length of string is not guaranteed to return ["a", "b", "c"]. According to the specs:

注意:按字符串长度排序[“a”,“b”,“c”]不保证返回[“a”,“b”,“c”]。根据规格:

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).

排序不一定稳定(即,比较相等的元素不一定保持原始顺序)。

If the objective is to sort by length then by dictionary order you must specify additional criteria:

如果目标是按长度排序,然后按字典顺序排序,则必须指定其他条件:

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});

#2


3  

Here is the sort, depending on the length of a string with javascript as you asked:

这是排序,取决于你问的javascript字符串的长度:

[the solution of the problem by bubble sort][1]

[通过冒泡排序解决问题] [1]

[1]: http://jsfiddle.net/sssonline2/vcme3/2/enter code here

[1]:http://jsfiddle.net/sssonline2/vcme3/2/enter code here here

#3


0  

Based on Salman's answer, I've written a small function to encapsulate it:

基于Salman的回答,我写了一个小函数来封装它:

function sortArrayByLength(arr, ascYN) {
        arr.sort(function (a, b) {           // sort array by length of text
            if (ascYN) return a.length - b.length;              // ASC -> a - b
            else return b.length - a.length;                    // DESC -> b - a
        });
    }

then just call it with

然后用它来调用它

sortArrayByLength( myArray, true );

Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.

请注意,遗憾的是,函数可以/不应该添加到Array原型中,如本页所述。

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!

此外,它修改了作为参数传递的数组,并且不返回任何内容。这会强制重复数组,对大型数组来说不会很好。如果有人有更好的想法,请发表评论!

#4


0  

I adapted @shareef's answer to make it concise. I use,

我改编了@ shareef的答案,使其简洁明了。我用,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

.sort(function(arg1,arg2){return arg1.length - arg2.length})

#5


0  

We can use Array.sort method to sort this array.

我们可以使用Array.sort方法对此数组进行排序。

ES5 solution

var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));

For ascending sort order: a.length - b.length

对于升序排序:a.length - b.length

For descending sort order: b.length - a.length

对于降序排序:b.length - a.length

ES6 solution

Attention: not all browsers can understand ES6 code!

注意:并非所有浏览器都能理解ES6代码!

In ES6 we can use an arrow function expressions.

在ES6中,我们可以使用箭头函数表达式。

let array = ["ab", "abcdefgh", "abcd"];

array.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(array, null, '\t'));

#6


-2  

<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

你传递给sort的匿名函数告诉它如何对给定的array.hope进行排序这会有所帮助。我知道这很令人困惑但是你可以通过传递一个函数作为参数来告诉sort函数如何对数组的元素进行排序它做什么

#1


149  

You can use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

您可以使用Array.sort方法对数组进行排序。将字符串长度视为排序标准的排序函数可以使用如下:

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});

Note: sorting ["a", "b", "c"] by length of string is not guaranteed to return ["a", "b", "c"]. According to the specs:

注意:按字符串长度排序[“a”,“b”,“c”]不保证返回[“a”,“b”,“c”]。根据规格:

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).

排序不一定稳定(即,比较相等的元素不一定保持原始顺序)。

If the objective is to sort by length then by dictionary order you must specify additional criteria:

如果目标是按长度排序,然后按字典顺序排序,则必须指定其他条件:

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});

#2


3  

Here is the sort, depending on the length of a string with javascript as you asked:

这是排序,取决于你问的javascript字符串的长度:

[the solution of the problem by bubble sort][1]

[通过冒泡排序解决问题] [1]

[1]: http://jsfiddle.net/sssonline2/vcme3/2/enter code here

[1]:http://jsfiddle.net/sssonline2/vcme3/2/enter code here here

#3


0  

Based on Salman's answer, I've written a small function to encapsulate it:

基于Salman的回答,我写了一个小函数来封装它:

function sortArrayByLength(arr, ascYN) {
        arr.sort(function (a, b) {           // sort array by length of text
            if (ascYN) return a.length - b.length;              // ASC -> a - b
            else return b.length - a.length;                    // DESC -> b - a
        });
    }

then just call it with

然后用它来调用它

sortArrayByLength( myArray, true );

Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.

请注意,遗憾的是,函数可以/不应该添加到Array原型中,如本页所述。

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!

此外,它修改了作为参数传递的数组,并且不返回任何内容。这会强制重复数组,对大型数组来说不会很好。如果有人有更好的想法,请发表评论!

#4


0  

I adapted @shareef's answer to make it concise. I use,

我改编了@ shareef的答案,使其简洁明了。我用,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

.sort(function(arg1,arg2){return arg1.length - arg2.length})

#5


0  

We can use Array.sort method to sort this array.

我们可以使用Array.sort方法对此数组进行排序。

ES5 solution

var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));

For ascending sort order: a.length - b.length

对于升序排序:a.length - b.length

For descending sort order: b.length - a.length

对于降序排序:b.length - a.length

ES6 solution

Attention: not all browsers can understand ES6 code!

注意:并非所有浏览器都能理解ES6代码!

In ES6 we can use an arrow function expressions.

在ES6中,我们可以使用箭头函数表达式。

let array = ["ab", "abcdefgh", "abcd"];

array.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(array, null, '\t'));

#6


-2  

<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

你传递给sort的匿名函数告诉它如何对给定的array.hope进行排序这会有所帮助。我知道这很令人困惑但是你可以通过传递一个函数作为参数来告诉sort函数如何对数组的元素进行排序它做什么