Javascript:如何在不移动-1数字的情况下对数组进行排序 [英] Javascript: how to sort array without moving -1 numbers

查看:86
本文介绍了Javascript:如何在不移动-1数字的情况下对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组`[-1,150,190,170,-1,-1,160,180]。我需要对这个数组进行排序,但是没有移动数字-1,所以它会返回[-1,150,160,170,-1,-1,180,190]。我怎么能这样做?



我尝试过的事情:



我试过这样的事情`



函数解(x){
var arr = [];
for(var i = 0; i< x.length; i ++){
if(x [i]!= -1){
arr.push(x [i]) ;
}
}
arr = arr.sort(function(a,b){return a-b});
var arr2 = [];
for(var i = 0; i< x.length; i ++){
if(x [i] == -1){
arr2.push(x [i]) ;
}
else {
arr2.push(?);
}
}
返回arr2;
}
console.log(解决方案([ - 1,150,190,170,-1,-1,180,160]));

解决方案

< blockquote>这就是我的看法:

 In = [-1, 150  190  170 , -  1,-1, 160  180 ]; 
// 在这里构建一个没有-1数字的过滤数组
过滤= [ 150 190 170 160 180 ];
// 此处进行正常排序
排序= [ 150 160 170 180 190 ];
// 这里通过合并来自In的-1和来自Sorted的值
Out = [-1, 150 160 170 , - 1,-1, 180 190 ];



[更新]

良好的开端,现在你需要建立相对于原始位置-1的数组

  function 解决方案(x){
var arr = [];
for var i = 0 ; i< x.length; i ++){
if (x [i]!= -1){
arr.push (X [1]);
}
}
arr = arr.sort( function (a,b){ return ab});
// 这里需要构建数组
// 就像你之前过滤x一样,你需要再次循环x
// 遇到-1时,将其推出数组
/ / 否则从arr获取下一个值
return arr;
}
console .log(解决方案([ - 1, 150 ,< span class =code-digit> 190 , 170 , - 1,-1, 180 160 ]));


I have an array` [-1,150,190,170,-1,-1,160,180]. I need to sort this array, but without moving the numbers -1, so it will return [-1,150,160,170,-1,-1,180,190].How can i do that?

What I have tried:

I have tried like this`

function solution(x){	
	var arr = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] != -1){
			arr.push(x[i]);
		}
	}
	arr = arr.sort(function(a,b){return a-b});
	var arr2 = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] == -1){
			arr2.push(x[i]);
		}
		else{
			arr2.push(?);
		}
	}
	return arr2;
}
console.log(solution([-1,150,190,170,-1,-1,180,160]));

解决方案

This is how I would see it:

In= [-1,150,190,170,-1,-1,160,180];
// here you build a filtered array without the -1 numbers
Filtered= [150,190,170,160,180];
// here do a normal sort
Sorted= [150,160,170,180,190];
// here build the Out array by merging the -1 from In and the values from Sorted
Out= [-1,150,160,170,-1,-1,180,190];


[Update]
Good start, now you need to build out array with respect to positions of -1 in original

function solution(x){	
	var arr = [];
	for(var i = 0; i < x.length; i++){
		if(x[i] != -1){
			arr.push(x[i]);
		}
	}
	arr = arr.sort(function(a,b){return a-b});
	// here you need to build out array
	// Just like you filtered x earlier, you need to loop again in x
	// when you encounter a -1, push it in out array
	// otherwise get next value from arr
	return arr;
}
console.log(solution([-1,150,190,170,-1,-1,180,160]));


这篇关于Javascript:如何在不移动-1数字的情况下对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆