JavaScript字符串数组排序

首发:http://windcoder.com/javascriptzifuchuanshuzupaixu/

代码:

                   var arry=["STEWARTS RT BEER 6/4/12 NR","7-UP 4/6/8 CN","",
						"1217-UP TEN 2/12 CN","DIET 7-UP 4/6/8 CN", 
						"1a1","FIJI 2/4/16.9 PET","",
						"1717A","1717","1717B","1716",
						"1716A","ABC","ABD","ACD","A123","A12D3","BCD","A123D",
						"FIJI 6/6/300 ML","FIJI 24/16.9 PET",
						"7-UP TEN 2/12 CN","217-UP TEN 2/12 CN"];
			var blnCheck = false;
			var i = arry.length,j;		
			while(i>0){	
					for(j=0;j<i-1;j++){
						tmpLen = Math.min(arry[j].length,arry[j+1].length);
						//当j+1为空时,交换(即将其排在最前),反之正常排序
						if(tmpLen===0&&arry[j+1].length === 0){							
								blnCheck = true;								
						}else{
							for(k=0;k<tmpLen;k++){
								//若arry[j][K]不为数字,j+1为数字   直接跳出,不需要交换
								if((arry[j][k].charCodeAt()<48||arry[j][k].charCodeAt()>57)
									&&(48<=arry[j+1][k].charCodeAt()&&arry[j+1][k].charCodeAt()<=57)){							
											break;
								}
								//若arry[j][K]为数字,j+1不为数字 交换顺序
								/*若arry[j][K]为数字,j+1为数字
								 *或arry[j][K]不为数字,i+1不为数字
								 * j>j+1 交换并跳出  j<j+1不交换并跳出
								 */ 
								if((48<=arry[j][k].charCodeAt()&&arry[j][k].charCodeAt()<=57)
								    &&(arry[j+1][k].charCodeAt()<47||arry[j+1][k].charCodeAt()>57)){
									blnCheck = true;                     	
									break;
								}else if(
									((48<=arry[j][k].charCodeAt()&&arry[j][k].charCodeAt()<=57)
										&&(48<=arry[j+1][k].charCodeAt()&&arry[j+1][k].charCodeAt()<=57))
									||((arry[j][k].charCodeAt()<48||arry[j][k].charCodeAt()>57)
										&&(arry[j+1][k].charCodeAt()<48||arry[j+1][k].charCodeAt()>57))){
									 if(arry[j][k]<arry[j+1][k]){ 
										break;
									 }
									 if(arry[j][k]>arry[j+1][k]){
										blnCheck = true;
										break;							 
									 }else  if((k==tmpLen-1&&arry[j][k]==arry[j+1][k])&&(arry[j].length>tmpLen)){
										blnCheck = true;
										break;
									 }		 
								} 								
							}
						}																		
						if (blnCheck) {
							tempExchangVal = arry[j];
							arry[j] = arry[j + 1];
							arry[j + 1] = tempExchangVal;
						}
						blnCheck = false;
					}					
					i--;
				}	 
			arry.forEach(function(e){
				document.write("</br>"+e+"</br>");
			});



效果:






ABC

ABD

ACD

A12D3

A123

A123D

BCD

DIET 7-UP 4/6/8 CN

FIJI 2/4/16.9 PET

FIJI 24/16.9 PET

FIJI 6/6/300 ML

STEWARTS RT BEER 6/4/12 NR

1a1

1217-UP TEN 2/12 CN

1716

1716A

1717

1717A

1717B

217-UP TEN 2/12 CN

7-UP TEN 2/12 CN

7-UP 4/6/8 CN

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值