如何使用javascript对数组的一部分进行排序? [英] How to sort a part of an array with javascript?

查看:89
本文介绍了如何使用javascript对数组的一部分进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多对象的数组.我正在尝试按升序对数组的前半部分进行排序.而且数组的后半部分也按升序排列.下面的代码是一个数组示例,也是我执行该操作的方法.我在想是否有一种更聪明的方法来提高代码的质量并获得相同的结果?有人可以帮忙吗?预先感谢!

I have an array having many objects. I am trying to sort the first half of the array with ascending order. And the second half of the array with ascending order too. The code below is an array example and my way to do it. I am thinking is there a smarter way to sharpen the code and get the same result? Can anyone help? Thanks in advance!

var data = [
    {id:1, x: 33},
    {id:2, x: 22},
    {id:3, x: 11},
    {id:4, x: 3},  
    {id:5, x: 2},
    {id:6, x: 1}  
];
var data1 = [];
for(var i=0; i<3; i++){
  data1.push(data[i]);
}
data1.sort (function(a,b) { return a.x - b.x; });

var data2 = [];
for(var i=3; i<6; i++){
  data2.push(data[i]);
}
data2.sort (function(a,b) { return a.x - b.x; });

data = data1.concat(data2);
console.log(data);

推荐答案

使用接头将其拧紧:

var data = [
    {id:1, x: 33},
    {id:2, x: 22},
    {id:3, x: 11},
    {id:4, x: 3},  
    {id:5, x: 2},
    {id:6, x: 1}  
];

// splice out and sort the first half of data
var data1 = data.splice(0,data.length / 2);
data1.sort (function(a,b) { return a.x - b.x; });

// sort the second half
data.sort (function(a,b) { return a.x - b.x; });

data = data1.concat(data);
console.log(data);

这篇关于如何使用javascript对数组的一部分进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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