Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.
试图从一个我知道只包含整数的数组中获取最大值和最小值似乎比我想象的要困难。
var numArray = [140000, 104, 99];
numArray = numArray.sort();
alert(numArray)
I'd expect this to show 99, 104, 140000
. Instead it shows 104, 140000, 99
. So it seems the sort is handling the values as strings.
我希望这能显示99,104,140000。取而代之的是104,1400,99。因此,排序似乎是将值作为字符串处理。
Is there a way to get the sort function to actually sort on integer value?
是否有办法让排序函数对整数值进行排序?
15 个解决方案
#1
697
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
默认情况下,sort方法按字母顺序对元素进行排序。要对数值排序,只需添加一个处理数值排序的新方法(sortNumber,如下所示)-
function sortNumber(a,b) {
return a - b;
}
var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
alert(numArray.join(","));
EDIT: using ES6 arrow functions:
编辑:使用ES6箭头功能:
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
#2
125
Just building on all of the above answers, they can also be done in one line like this:
在以上所有答案的基础上,也可以这样一行完成:
var numArray = [140000, 104, 99];
// ES5
numArray = numArray.sort(function (a, b) { return a - b; });
// ES2015
numArray = numArray.sort((a, b) => a - b);
//outputs: 99, 104, 140000
#3
60
array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here's a simple example:
数组中。sort默认执行字典排序,对于数字排序,提供您自己的函数。这是一个简单的例子:
function compareNumbers(a, b)
{
return a - b;
}
numArray.sort(compareNumbers);
Also note that sort works "in place", there's no need for the assignment.
还要注意排序是“到位”的,不需要分配任务。
#4
30
This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:
这个答案与现有的一些答案相同,但是ECMAScript 6 arrow函数提供了更紧凑的语法,允许我们在不牺牲可读性的情况下定义内联排序函数:
numArray = numArray.sort((a, b) => a - b);
It is supported in most browsers today.
现在大多数浏览器都支持它。
#5
13
I agree with aks, however instead of using
然而,我同意aks,而不是使用
return a - b;
You should use
你应该使用
return a > b ? 1 : a < b ? -1 : 0;
#6
9
In JavaScript the sort() method's default behaviour is to sort values in an array alphabetically.
在JavaScript中,sort()方法的默认行为是按字母顺序对数组中的值进行排序。
To sort by number you have to define a numeric sort function (which is very easy):
要按数字排序,你必须定义一个数值排序函数(这很容易):
...
function sortNumber(a, b)
{
return a - b;
}
numArray = numArray.sort(sortNumber);
#7
6
Array.prototype.sort() is the go to method for sorting arrays, but there are a couple of issues we need to be aware of.
sort()是排序数组的go to方法,但是我们需要注意一些问题。
The sorting order is by default lexicographic and not numeric regardless of the types of values in the array. Even if the array is all numbers, all values will be converted to string and sorted lexicographically.
排序顺序是默认的字典顺序,而不是数字,无论数组中的值是什么类型。即使数组是所有的数字,所有的值都将被转换为字符串并按字典顺序排序。
So should we need to customize the sort() and reverse() method like below.
因此,我们是否需要定制sort()和reverse()方法,如下所示。
引用URL
For sorting numbers inside the array
用于对数组中的数字进行排序。
numArray.sort(function(a, b)
{
return a - b;
});
For reversing numbers inside the array
用于反转数组中的数字
numArray.sort(function(a, b)
{
return b - a;
});
引用URL
#8
3
The question has already been answered, the shortest way is to use sort()
method. But if you're searching for more ways to sort your array of numbers, and you also love cycles, check the following
问题已经得到了回答,最短的方法是使用sort()方法。但是,如果您正在寻找更多的方法来对数字数组进行排序,并且您也喜欢循环,请检查以下内容
Insertion sort
插入排序
Ascending:
提升:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
var target = numArray[i];
for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {
numArray[j+1] = numArray[j];
}
numArray[j+1] = target
}
console.log(numArray);
Descending:
降:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
var target = numArray[i];
for (var j = i - 1; j >= 0 && (numArray[j] < target); j--) {
numArray[j+1] = numArray[j];
}
numArray[j+1] = target
}
console.log(numArray);
Selection sort:
选择排序:
Ascending:
提升:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
var min = i;
for (var j = i + 1; j < numArray.length; j++) {
if (numArray[j] < numArray[min]) {
min = j;
}
}
if (min != i) {
var target = numArray[i];
numArray[i] = numArray[min];
numArray[min] = target;
}
}
console.log(numArray);
Descending:
降:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
var min = i;
for (var j = i + 1; j < numArray.length; j++) {
if (numArray[j] > numArray[min]) {
min = j;
}
}
if (min != i) {
var target = numArray[i];
numArray[i] = numArray[min];
numArray[min] = target;
}
}
console.log(numArray);
Have fun
玩得开心
#9
2
For a normal array of elements values only:
只适用于一般的元素数组:
function sortArrayOfElements(arrayToSort) {
function compareElements(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
return arrayToSort.sort(compareElements);
}
e.g. 1:
var array1 = [1,2,545,676,64,2,24]
**output : [1, 2, 2, 24, 64, 545, 676]**
var array2 = ["v","a",545,676,64,2,"24"]
**output: ["a", "v", 2, "24", 64, 545, 676]**
For an array of objects:
对象数组:
function sortArrayOfObjects(arrayToSort, key) {
function compareObjects(a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
}
return arrayToSort.sort(compareObjects);
}
e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]
**output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]**
#10
2
Try this code as below
试试下面的代码
var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;}
alert(sortA(a));
#11
1
Update! Scroll to bottom of answer for
smartSort
prop additive that gives even more fun!
Sorts arrays of anything!更新!滚动到底部的答案为smartSort道具添加剂,提供更多的乐趣!排序数组的任何东西!
My personal favorite form of this function allows for a param for Ascending, or Descending:
我个人最喜欢的函数形式允许升序或降序:
function intArraySort(c, a) {
function d(a, b) { return b - a; }
"string" == typeof a && a.toLowerCase();
switch (a) {
default: return c.sort(function(a, b) { return a - b; });
case 1:
case "d":
case "dc":
case "desc":
return c.sort(d)
}
};
Usage as simple as:
使用简单:
var ara = function getArray() {
var a = Math.floor(Math.random()*50)+1, b = [];
for (i=0;i<=a;i++) b.push(Math.floor(Math.random()*50)+1);
return b;
}();
// Ascending
intArraySort(ara);
console.log(ara);
// Descending
intArraySort(ara, 1);
console.log(ara);
// Ascending
intArraySort(ara, 'a');
console.log(ara);
// Descending
intArraySort(ara, 'dc');
console.log(ara);
// Ascending
intArraySort(ara, 'asc');
console.log(ara);
jsFiddle
Or Code Snippet Example Here!
function intArraySort(c, a) {
function d(a, b) { return b - a }
"string" == typeof a && a.toLowerCase();
switch (a) {
default: return c.sort(function(a, b) { return a - b });
case 1:
case "d":
case "dc":
case "desc":
return c.sort(d)
}
};
function tableExample() {
var d = function() {
var a = Math.floor(50 * Math.random()) + 1,
b = [];
for (i = 0; i <= a; i++) b.push(Math.floor(50 * Math.random()) + 1);
return b
},
a = function(a) {
var b = $("<tr/>"),
c = $("<th/>").prependTo(b);
$("<td/>", {
text: intArraySort(d(), a).join(", ")
}).appendTo(b);
switch (a) {
case 1:
case "d":
case "dc":
case "desc":
c.addClass("desc").text("Descending");
break;
default:
c.addClass("asc").text("Ascending")
}
return b
};
return $("tbody").empty().append(a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1))
};
tableExample();
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }
.asc { color: red; }
.desc { color: blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table><tbody></tbody></table>
.smartSort('asc' | 'desc')
Now have even more fun with a sorting method that sorts an array full of multiple items! Doesn't currently cover "associative" (aka, string keys), but it does cover about every type of value! Not only will it sort the multiple values asc
or desc
accordingly, but it will also maintain constant "position" of "groups" of values. In other words; ints are always first, then come strings, then arrays (yes, i'm making this multidimensional!), then Objects (unfiltered, element, date), & finally undefineds and nulls!
现在,使用排序方法对一个满是多个条目的数组进行排序,将会更加有趣!目前还没有涉及到“关联”(即字符串键),但它确实涉及了几乎所有类型的值!它不仅会相应地对多个值进行排序,而且还会保持“组”值的“位置”。换句话说;ints总是首先出现,然后是字符串,然后是数组(是的,我正在创建这个多维度的!),然后是对象(未过滤的,元素,日期),最后是不定义和无效!
"Why?" you ask. Why not!
“为什么?”你问。为什么不呢!
Now comes in 2 flavors! The first of which requires newer browsers as it uses Object.defineProperty
to add the method to the Array.protoype
Object. This allows for ease of natural use, such as: myArray.smartSort('a')
. If you need to implement for older browsers, or you simply don't like modifying native Objects, scroll down to Method Only version.
现在有两种口味!第一个需要更新的浏览器,因为它使用Object.defineProperty向数组添加方法。protoype对象。这允许自然使用,例如:myArray.smartSort(“a”)。如果您需要为旧的浏览器实现,或者您只是不喜欢修改本机对象,那么请向下滚动到只有方法的版本。
/* begin */
/* KEY NOTE! Requires EcmaScript 5.1 (not compatible with older browsers) */
;;(function(){if(Object.defineProperty&&!Array.prototype.smartSort){var h=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a>b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("a");b instanceof Array&&b.smartSort("a");if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("a"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("a"),a.id==e[0]?1:-1;e=[a.tagName, b.tagName].smartSort("a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("a"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d"); return a[d].tagName==c[0]?1:-1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]>g[1]},k=function(a,b){if(null== a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("d");b instanceof Array&&b.smartSort("d");if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("d"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("d"),a.id==e[0]?-1:1;e=[a.tagName,b.tagName].smartSort("d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("d"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1;if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]};Object.defineProperty(Array.prototype,"smartSort",{value:function(){return arguments&& (!arguments.length||1==arguments.length&&/^a([sc]{2})?$|^d([esc]{3})?$/i.test(arguments[0]))?this.sort(!arguments.length||/^a([sc]{2})?$/i.test(arguments[0])?h:k):this.sort()}})}})();
/* end */
jsFiddle Array.prototype.smartSort('asc|desc')
Use is simple! First make some crazy array like:
使用很简单!首先制作一些疯狂的数组,比如:
window.z = [ 'one', undefined, $('<span />'), 'two', null, 2, $('<div />', { id: 'Thing' }), $('<div />'), 4, $('<header />') ];
z.push(new Date('1/01/2011'));
z.push('three');
z.push(undefined);
z.push([ 'one', 'three', 'four' ]);
z.push([ 'one', 'three', 'five' ]);
z.push({ a: 'a', b: 'b' });
z.push({ name: 'bob', value: 'bill' });
z.push(new Date());
z.push({ john: 'jill', jack: 'june' });
z.push([ 'abc', 'def', [ 'abc', 'def', 'cba' ], [ 'cba', 'def', 'bca' ], 'cba' ]);
z.push([ 'cba', 'def', 'bca' ]);
z.push({ a: 'a', b: 'b', c: 'c' });
z.push({ a: 'a', b: 'b', c: 'd' });
Then simply sort it!
然后简单地解决它!
z.smartSort('asc'); // Ascending
z.smartSort('desc'); // Descending
Method Only
Same as the preceding, except as just a simple method!
和前面一样,除了一个简单的方法!
/* begin */
/* KEY NOTE! Method `smartSort` is appended to native `window` for global use. If you'd prefer a more local scope, simple change `window.smartSort` to `var smartSort` and place inside your class/method */
window.smartSort=function(){if(arguments){var a,b,c;for(c in arguments)arguments[c]instanceof Array&&(a=arguments[c],void 0==b&&(b="a")),"string"==typeof arguments[c]&&(b=/^a([sc]{2})?$/i.test(arguments[c])?"a":"d");if(a instanceof Array)return a.sort("a"==b?smartSort.asc:smartSort.desc)}return this.sort()};smartSort.asc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a> b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.asc);b instanceof Array&&b.sort(smartSort.asc);if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c], b[c]],"a"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"a"),a.id==e[0]?1:-1;e=smartSort([a.tagName,b.tagName],"a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g), "a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"a"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"a");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1; if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==c[0]?1:-1}g=[a,b].sort();return g[0]>g[1]};smartSort.desc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)? 1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.desc);b instanceof Array&&b.sort(smartSort.desc);if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c],b[c]],"d"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]], b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"d"),a.id==e[0]?-1:1;e=smartSort([a.tagName,b.tagName],"d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g),"a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&& b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"d"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1; if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]}
/* end */
Use:
使用:
z = smartSort(z, 'asc'); // Ascending
z = smartSort(z, 'desc'); // Descending
jsFiddle Method smartSort(Array, "asc|desc")
#12
1
Try this code:
试试这段代码:
HTML:
HTML:
<div id="demo"></div>
JavaScript code:
JavaScript代码:
<script>
(function(){
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
})();
</script>
#13
1
The reason why the sort function behaves so weird
From the documentation:
从文档:
[...] the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
[…该数组根据每个字符的Unicode编码点值,根据每个元素的字符串转换进行排序。
If you print the unicode point values of the array then it will get clear.
如果您打印数组的unicode点值,那么它将变得清晰。
console.log("140000".charCodeAt(0));
console.log("104".charCodeAt(0));
console.log("99".charCodeAt(0));
//Note that we only look at the first index of the number "charCodeAt( 0 )"
This returns: "49, 49, 57".
返回:49 49 49 57。
49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)
Now, because 140000 and 104 returned the same values (49) it cuts the first index and checks again:
现在,因为140000和104返回了相同的值(49),它削减了第一个索引并再次检查:
console.log("40000".charCodeAt(0));
console.log("04".charCodeAt(0));
//Note that we only look at the first index of the number "charCodeAt( 0 )"
52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)
If we sort this, then we will get:
如果我们对它进行排序,我们会得到:
40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)
so 104 comes before 140000.
104是在140000之前。
So the final result will be:
所以最终的结果是:
var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)
104, 140000, 99
104、140000、99
Conclusion:
结论:
sort()
does sorting by only looking at the first index of the numbers. sort()
does not care if a whole number is bigger than another, it compares the value of the unicode of the digits, and if there are two equal unicode values, then it checks if there is a next digit and compares it as well.
sort()只查看数字的第一个索引来进行排序。sort()不关心整个数字是否大于另一个,它比较数字的unicode值,如果有两个相等的unicode值,那么它检查是否有下一个数字,并对它进行比较。
To sort correctly, you have to pass a compare function to sort()
like explained here.
要正确排序,您必须传递一个compare函数到sort(),就像这里解释的那样。
#14
0
Here is my sort array function in the utils library:
这是我在utils库中的排序数组函数:
sortArray: function(array) {
array.sort(function(a, b) {
return a > b;
});
},
# Let's test a string array
var arr = ['bbc', 'chrome', 'aux', 'ext', 'dog'];
utils.sortArray(arr);
console.log(arr);
>>> ["aux", "bbc", "chrome", "dog", "ext", remove: function]
# Let's test a number array
var arr = [55, 22, 1425, 12, 78];
utils.sortArray(arr);
console.log(arr);
>>> [12, 22, 55, 78, 1425, remove: function]
#15
0
In case if you want it done in pure javascript. Go by this piece of code.
如果你想要用纯javascript完成的话。通过这段代码。
function sort(arr){
var len = arr.length;
for (var i = 0; i<=len-1; i++){ //loop for array length-1 times(because first index starts fom 0)
for(var j = i+1; j<=len-1; j++){ // loop every time starting from i value till length-1 of array
if(arr[i]>arr[j]){ // this condition do the checking if current ith value is bigger than current jth value. You can alter this condition if you need descending array.
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
console.log(sort([7,5,2,4,3,9])) // add your choice of data here what you want to be sorted
alert(sort([7,5,2,4,3,9]))
#1
697
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
默认情况下,sort方法按字母顺序对元素进行排序。要对数值排序,只需添加一个处理数值排序的新方法(sortNumber,如下所示)-
function sortNumber(a,b) {
return a - b;
}
var numArray = [140000, 104, 99];
numArray.sort(sortNumber);
alert(numArray.join(","));
EDIT: using ES6 arrow functions:
编辑:使用ES6箭头功能:
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
#2
125
Just building on all of the above answers, they can also be done in one line like this:
在以上所有答案的基础上,也可以这样一行完成:
var numArray = [140000, 104, 99];
// ES5
numArray = numArray.sort(function (a, b) { return a - b; });
// ES2015
numArray = numArray.sort((a, b) => a - b);
//outputs: 99, 104, 140000
#3
60
array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here's a simple example:
数组中。sort默认执行字典排序,对于数字排序,提供您自己的函数。这是一个简单的例子:
function compareNumbers(a, b)
{
return a - b;
}
numArray.sort(compareNumbers);
Also note that sort works "in place", there's no need for the assignment.
还要注意排序是“到位”的,不需要分配任务。
#4
30
This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:
这个答案与现有的一些答案相同,但是ECMAScript 6 arrow函数提供了更紧凑的语法,允许我们在不牺牲可读性的情况下定义内联排序函数:
numArray = numArray.sort((a, b) => a - b);
It is supported in most browsers today.
现在大多数浏览器都支持它。
#5
13
I agree with aks, however instead of using
然而,我同意aks,而不是使用
return a - b;
You should use
你应该使用
return a > b ? 1 : a < b ? -1 : 0;
#6
9
In JavaScript the sort() method's default behaviour is to sort values in an array alphabetically.
在JavaScript中,sort()方法的默认行为是按字母顺序对数组中的值进行排序。
To sort by number you have to define a numeric sort function (which is very easy):
要按数字排序,你必须定义一个数值排序函数(这很容易):
...
function sortNumber(a, b)
{
return a - b;
}
numArray = numArray.sort(sortNumber);
#7
6
Array.prototype.sort() is the go to method for sorting arrays, but there are a couple of issues we need to be aware of.
sort()是排序数组的go to方法,但是我们需要注意一些问题。
The sorting order is by default lexicographic and not numeric regardless of the types of values in the array. Even if the array is all numbers, all values will be converted to string and sorted lexicographically.
排序顺序是默认的字典顺序,而不是数字,无论数组中的值是什么类型。即使数组是所有的数字,所有的值都将被转换为字符串并按字典顺序排序。
So should we need to customize the sort() and reverse() method like below.
因此,我们是否需要定制sort()和reverse()方法,如下所示。
引用URL
For sorting numbers inside the array
用于对数组中的数字进行排序。
numArray.sort(function(a, b)
{
return a - b;
});
For reversing numbers inside the array
用于反转数组中的数字
numArray.sort(function(a, b)
{
return b - a;
});
引用URL
#8
3
The question has already been answered, the shortest way is to use sort()
method. But if you're searching for more ways to sort your array of numbers, and you also love cycles, check the following
问题已经得到了回答,最短的方法是使用sort()方法。但是,如果您正在寻找更多的方法来对数字数组进行排序,并且您也喜欢循环,请检查以下内容
Insertion sort
插入排序
Ascending:
提升:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
var target = numArray[i];
for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {
numArray[j+1] = numArray[j];
}
numArray[j+1] = target
}
console.log(numArray);
Descending:
降:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
var target = numArray[i];
for (var j = i - 1; j >= 0 && (numArray[j] < target); j--) {
numArray[j+1] = numArray[j];
}
numArray[j+1] = target
}
console.log(numArray);
Selection sort:
选择排序:
Ascending:
提升:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
var min = i;
for (var j = i + 1; j < numArray.length; j++) {
if (numArray[j] < numArray[min]) {
min = j;
}
}
if (min != i) {
var target = numArray[i];
numArray[i] = numArray[min];
numArray[min] = target;
}
}
console.log(numArray);
Descending:
降:
var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
var min = i;
for (var j = i + 1; j < numArray.length; j++) {
if (numArray[j] > numArray[min]) {
min = j;
}
}
if (min != i) {
var target = numArray[i];
numArray[i] = numArray[min];
numArray[min] = target;
}
}
console.log(numArray);
Have fun
玩得开心
#9
2
For a normal array of elements values only:
只适用于一般的元素数组:
function sortArrayOfElements(arrayToSort) {
function compareElements(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
return arrayToSort.sort(compareElements);
}
e.g. 1:
var array1 = [1,2,545,676,64,2,24]
**output : [1, 2, 2, 24, 64, 545, 676]**
var array2 = ["v","a",545,676,64,2,"24"]
**output: ["a", "v", 2, "24", 64, 545, 676]**
For an array of objects:
对象数组:
function sortArrayOfObjects(arrayToSort, key) {
function compareObjects(a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
}
return arrayToSort.sort(compareObjects);
}
e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]
**output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]**
#10
2
Try this code as below
试试下面的代码
var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;}
alert(sortA(a));
#11
1
Update! Scroll to bottom of answer for
smartSort
prop additive that gives even more fun!
Sorts arrays of anything!更新!滚动到底部的答案为smartSort道具添加剂,提供更多的乐趣!排序数组的任何东西!
My personal favorite form of this function allows for a param for Ascending, or Descending:
我个人最喜欢的函数形式允许升序或降序:
function intArraySort(c, a) {
function d(a, b) { return b - a; }
"string" == typeof a && a.toLowerCase();
switch (a) {
default: return c.sort(function(a, b) { return a - b; });
case 1:
case "d":
case "dc":
case "desc":
return c.sort(d)
}
};
Usage as simple as:
使用简单:
var ara = function getArray() {
var a = Math.floor(Math.random()*50)+1, b = [];
for (i=0;i<=a;i++) b.push(Math.floor(Math.random()*50)+1);
return b;
}();
// Ascending
intArraySort(ara);
console.log(ara);
// Descending
intArraySort(ara, 1);
console.log(ara);
// Ascending
intArraySort(ara, 'a');
console.log(ara);
// Descending
intArraySort(ara, 'dc');
console.log(ara);
// Ascending
intArraySort(ara, 'asc');
console.log(ara);
jsFiddle
Or Code Snippet Example Here!
function intArraySort(c, a) {
function d(a, b) { return b - a }
"string" == typeof a && a.toLowerCase();
switch (a) {
default: return c.sort(function(a, b) { return a - b });
case 1:
case "d":
case "dc":
case "desc":
return c.sort(d)
}
};
function tableExample() {
var d = function() {
var a = Math.floor(50 * Math.random()) + 1,
b = [];
for (i = 0; i <= a; i++) b.push(Math.floor(50 * Math.random()) + 1);
return b
},
a = function(a) {
var b = $("<tr/>"),
c = $("<th/>").prependTo(b);
$("<td/>", {
text: intArraySort(d(), a).join(", ")
}).appendTo(b);
switch (a) {
case 1:
case "d":
case "dc":
case "desc":
c.addClass("desc").text("Descending");
break;
default:
c.addClass("asc").text("Ascending")
}
return b
};
return $("tbody").empty().append(a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1))
};
tableExample();
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }
.asc { color: red; }
.desc { color: blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table><tbody></tbody></table>
.smartSort('asc' | 'desc')
Now have even more fun with a sorting method that sorts an array full of multiple items! Doesn't currently cover "associative" (aka, string keys), but it does cover about every type of value! Not only will it sort the multiple values asc
or desc
accordingly, but it will also maintain constant "position" of "groups" of values. In other words; ints are always first, then come strings, then arrays (yes, i'm making this multidimensional!), then Objects (unfiltered, element, date), & finally undefineds and nulls!
现在,使用排序方法对一个满是多个条目的数组进行排序,将会更加有趣!目前还没有涉及到“关联”(即字符串键),但它确实涉及了几乎所有类型的值!它不仅会相应地对多个值进行排序,而且还会保持“组”值的“位置”。换句话说;ints总是首先出现,然后是字符串,然后是数组(是的,我正在创建这个多维度的!),然后是对象(未过滤的,元素,日期),最后是不定义和无效!
"Why?" you ask. Why not!
“为什么?”你问。为什么不呢!
Now comes in 2 flavors! The first of which requires newer browsers as it uses Object.defineProperty
to add the method to the Array.protoype
Object. This allows for ease of natural use, such as: myArray.smartSort('a')
. If you need to implement for older browsers, or you simply don't like modifying native Objects, scroll down to Method Only version.
现在有两种口味!第一个需要更新的浏览器,因为它使用Object.defineProperty向数组添加方法。protoype对象。这允许自然使用,例如:myArray.smartSort(“a”)。如果您需要为旧的浏览器实现,或者您只是不喜欢修改本机对象,那么请向下滚动到只有方法的版本。
/* begin */
/* KEY NOTE! Requires EcmaScript 5.1 (not compatible with older browsers) */
;;(function(){if(Object.defineProperty&&!Array.prototype.smartSort){var h=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a>b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("a");b instanceof Array&&b.smartSort("a");if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("a"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("a"),a.id==e[0]?1:-1;e=[a.tagName, b.tagName].smartSort("a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("a"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d"); return a[d].tagName==c[0]?1:-1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]>g[1]},k=function(a,b){if(null== a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("d");b instanceof Array&&b.smartSort("d");if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("d"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("d"),a.id==e[0]?-1:1;e=[a.tagName,b.tagName].smartSort("d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("d"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1;if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]};Object.defineProperty(Array.prototype,"smartSort",{value:function(){return arguments&& (!arguments.length||1==arguments.length&&/^a([sc]{2})?$|^d([esc]{3})?$/i.test(arguments[0]))?this.sort(!arguments.length||/^a([sc]{2})?$/i.test(arguments[0])?h:k):this.sort()}})}})();
/* end */
jsFiddle Array.prototype.smartSort('asc|desc')
Use is simple! First make some crazy array like:
使用很简单!首先制作一些疯狂的数组,比如:
window.z = [ 'one', undefined, $('<span />'), 'two', null, 2, $('<div />', { id: 'Thing' }), $('<div />'), 4, $('<header />') ];
z.push(new Date('1/01/2011'));
z.push('three');
z.push(undefined);
z.push([ 'one', 'three', 'four' ]);
z.push([ 'one', 'three', 'five' ]);
z.push({ a: 'a', b: 'b' });
z.push({ name: 'bob', value: 'bill' });
z.push(new Date());
z.push({ john: 'jill', jack: 'june' });
z.push([ 'abc', 'def', [ 'abc', 'def', 'cba' ], [ 'cba', 'def', 'bca' ], 'cba' ]);
z.push([ 'cba', 'def', 'bca' ]);
z.push({ a: 'a', b: 'b', c: 'c' });
z.push({ a: 'a', b: 'b', c: 'd' });
Then simply sort it!
然后简单地解决它!
z.smartSort('asc'); // Ascending
z.smartSort('desc'); // Descending
Method Only
Same as the preceding, except as just a simple method!
和前面一样,除了一个简单的方法!
/* begin */
/* KEY NOTE! Method `smartSort` is appended to native `window` for global use. If you'd prefer a more local scope, simple change `window.smartSort` to `var smartSort` and place inside your class/method */
window.smartSort=function(){if(arguments){var a,b,c;for(c in arguments)arguments[c]instanceof Array&&(a=arguments[c],void 0==b&&(b="a")),"string"==typeof arguments[c]&&(b=/^a([sc]{2})?$/i.test(arguments[c])?"a":"d");if(a instanceof Array)return a.sort("a"==b?smartSort.asc:smartSort.desc)}return this.sort()};smartSort.asc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a> b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.asc);b instanceof Array&&b.sort(smartSort.asc);if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c], b[c]],"a"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"a"),a.id==e[0]?1:-1;e=smartSort([a.tagName,b.tagName],"a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g), "a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"a"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"a");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1; if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==c[0]?1:-1}g=[a,b].sort();return g[0]>g[1]};smartSort.desc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)? 1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.desc);b instanceof Array&&b.sort(smartSort.desc);if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c],b[c]],"d"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]], b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"d"),a.id==e[0]?-1:1;e=smartSort([a.tagName,b.tagName],"d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g),"a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&& b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"d"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1; if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]}
/* end */
Use:
使用:
z = smartSort(z, 'asc'); // Ascending
z = smartSort(z, 'desc'); // Descending
jsFiddle Method smartSort(Array, "asc|desc")
#12
1
Try this code:
试试这段代码:
HTML:
HTML:
<div id="demo"></div>
JavaScript code:
JavaScript代码:
<script>
(function(){
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
})();
</script>
#13
1
The reason why the sort function behaves so weird
From the documentation:
从文档:
[...] the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.
[…该数组根据每个字符的Unicode编码点值,根据每个元素的字符串转换进行排序。
If you print the unicode point values of the array then it will get clear.
如果您打印数组的unicode点值,那么它将变得清晰。
console.log("140000".charCodeAt(0));
console.log("104".charCodeAt(0));
console.log("99".charCodeAt(0));
//Note that we only look at the first index of the number "charCodeAt( 0 )"
This returns: "49, 49, 57".
返回:49 49 49 57。
49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)
Now, because 140000 and 104 returned the same values (49) it cuts the first index and checks again:
现在,因为140000和104返回了相同的值(49),它削减了第一个索引并再次检查:
console.log("40000".charCodeAt(0));
console.log("04".charCodeAt(0));
//Note that we only look at the first index of the number "charCodeAt( 0 )"
52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)
If we sort this, then we will get:
如果我们对它进行排序,我们会得到:
40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)
so 104 comes before 140000.
104是在140000之前。
So the final result will be:
所以最终的结果是:
var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)
104, 140000, 99
104、140000、99
Conclusion:
结论:
sort()
does sorting by only looking at the first index of the numbers. sort()
does not care if a whole number is bigger than another, it compares the value of the unicode of the digits, and if there are two equal unicode values, then it checks if there is a next digit and compares it as well.
sort()只查看数字的第一个索引来进行排序。sort()不关心整个数字是否大于另一个,它比较数字的unicode值,如果有两个相等的unicode值,那么它检查是否有下一个数字,并对它进行比较。
To sort correctly, you have to pass a compare function to sort()
like explained here.
要正确排序,您必须传递一个compare函数到sort(),就像这里解释的那样。
#14
0
Here is my sort array function in the utils library:
这是我在utils库中的排序数组函数:
sortArray: function(array) {
array.sort(function(a, b) {
return a > b;
});
},
# Let's test a string array
var arr = ['bbc', 'chrome', 'aux', 'ext', 'dog'];
utils.sortArray(arr);
console.log(arr);
>>> ["aux", "bbc", "chrome", "dog", "ext", remove: function]
# Let's test a number array
var arr = [55, 22, 1425, 12, 78];
utils.sortArray(arr);
console.log(arr);
>>> [12, 22, 55, 78, 1425, remove: function]
#15
0
In case if you want it done in pure javascript. Go by this piece of code.
如果你想要用纯javascript完成的话。通过这段代码。
function sort(arr){
var len = arr.length;
for (var i = 0; i<=len-1; i++){ //loop for array length-1 times(because first index starts fom 0)
for(var j = i+1; j<=len-1; j++){ // loop every time starting from i value till length-1 of array
if(arr[i]>arr[j]){ // this condition do the checking if current ith value is bigger than current jth value. You can alter this condition if you need descending array.
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
console.log(sort([7,5,2,4,3,9])) // add your choice of data here what you want to be sorted
alert(sort([7,5,2,4,3,9]))