You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functioncompare(a,b){if(aislessthanbbysomeorderingcriterion){return-1;}if(aisgreaterthanbbytheorderingcriterion){return1;}// a must be equal to breturn0;}
varitems=[{name: 'Edward',value: 21},{name: 'Sharpe',value: 37},{name: 'And',value: 45},{name: 'The',value: -12},{name: 'Magnetic',value: 13},{name: 'Zeros',value: 37}];// sort by valueitems.sort(function(a,b){returna.value-b.value;});// sort by nameitems.sort(function(a,b){varnameA=a.name.toUpperCase();// ignore upper and lowercasevarnameB=b.name.toUpperCase();// ignore upper and lowercaseif(nameA<nameB){return-1;}if(nameA>nameB){return1;}// names must be equalreturn0;});
创建、展示和排序数组
全是字符串(普通字符)
全是字符串(数字字符)
全是数字
既有数字也有普通字符串
varstringArray=['Blue','Humpback','Beluga'];varnumericStringArray=['80','9','700'];varnumberArray=[40,1,5,200];varmixedNumericArray=['80','9','700',40,1,5,200];functioncompareNumbers(a,b){returna-b;}console.log('stringArray:',stringArray.join());console.log('Sorted:',stringArray.sort());console.log('numberArray:',numberArray.join());console.log('Sorted without a compare function:',numberArray.sort());console.log('Sorted with compareNumbers:',numberArray.sort(compareNumbers));console.log('numericStringArray:',numericStringArray.join());console.log('Sorted without a compare function:',numericStringArray.sort());console.log('Sorted with compareNumbers:',numericStringArray.sort(compareNumbers));console.log('mixedNumericArray:',mixedNumericArray.join());console.log('Sorted without a compare function:',mixedNumericArray.sort());console.log('Sorted with compareNumbers:',mixedNumericArray.sort(compareNumbers));
对于类似e, é, è, a, ä这样的字符来说,可以通过String.localeCompare进行排序。
varitems=['réservé','premier','communiqué','café','adieu','éclair'];items.sort(function(a,b){returna.localeCompare(b);});// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
map()结合sort()一起使用
// the array to be sortedvarlist=['Delta','alpha','CHARLIE','bravo'];// temporary array holds objects with position and sort-valuevarmapped=list.map(function(el,i){return{index: i,value: el.toLowerCase()};})// sorting the mapped array containing the reduced valuesmapped.sort(function(a,b){if(a.value>b.value){return1;}if(a.value<b.value){return-1;}return0;});// container for the resulting ordervarresult=mapped.map(function(el){returnlist[el.index];});// ["alpha", "bravo", "CHARLIE", "Delta"]
// the array to be sortedvarlist=['Delta','alpha','CHARLIE','bravo'];// temporary array holds objects with position and sort-valuevarmapped=list.map(function(el,i){return{index: i,value: el.toLowerCase(),meta: el,};})// sorting the mapped array containing the reduced valuesmapped.sort(function(a,b){if(a.value>b.value){return1;}if(a.value<b.value){return-1;}return0;});varresult=mapped.map(function(el){returnel.meta});// ["alpha", "bravo", "CHARLIE", "Delta"]
初识sort()
举例说明"将元素转换为字符串":
["a","A"].sort()//["A","a"]
这是因为a的码为97,A的码为65[111, 2].sort();//[111, 2]
这是因为1的码为49"111".charCodeAt();//49
,2的码为50"2".charCodeAt();//50
sort() demo
sort() 语法
比较函数compareFunction
sort() 升降序规则(重点)
compareFunction(a, b)
的返回值小于0,a的index值比b小,升序排列。[1,9,2,3,4,5,6,"foo","bar","baz"].sort((a,b)=>a-b);// [1, 2, 3, 4, 5, 6, 9, "foo", "bar", "baz"]
compareFunction(a, b)
的返回值等于0,保持a和b的相对位置不变,再对其他不同的元素进行排序。compareFunction(a, b)
返回的值大于0,b的index值比a小,降序排列。compareFunction(a, b)
必须总是返回相同的值,当给定一对特定的元素a和b作为它的两个参数时。如果返回的结果不一致,则未定义排序顺序。比较函数伪代码:
为了比较数字而不是字符串,可以对a,b做减法运算
sort函数可以直接运行匿名函数:
箭头函数写法:
根据对象的一个属性排序:
创建、展示和排序数组
排序non-ASCII字符
对于类似e, é, è, a, ä这样的字符来说,可以通过String.localeCompare进行排序。
map()结合sort()一起使用
条件改为
if (a.value < b.value) { return 1; } if (a.value > b.value) { return -1; }
时,变为降序。也可以加一个meta,改为:
对象根据value给key排序
有一个高级用法:对象根据value给key排序。
leetcode347.前K个高频元素可以通过这个特性做出来:
题解位于:https://github.com/FrankKai/leetcode-js/blob/master/347.Top_K_Frequent_Elements.js
总结
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The text was updated successfully, but these errors were encountered: