在 JavaScript 中分别对数组的各个部分进行排序
javascriptweb developmentfront end technologyobject oriented programming
我们有一个包含许多对象的数组。我们需要编写一个函数对数组的前半部分按升序排序。
数组的后半部分按升序排序,但不将两半的条目混合在一起。
考虑这个示例数组 −
const arr = [
{id:1, x: 33},
{id:2, x: 22},
{id:3, x: 11},
{id:4, x: 3},
{id:5, x: 2},
{id:6, x: 1}
];
我们的函数应该根据对象的 'x' 属性对该数组进行排序,同时牢记上述内容。
示例
其代码为 −
const arr = [
{id:1, x: 33},
{id:2, x: 22},
{id:3, x: 11},
{id:4, x: 3},
{id:5, x: 2},
{id:6, x: 1}
];
const sortInParts = array => {
const arr = array.slice();
const sorter = (a, b) => {
return a['x'] - b['x'];
};
const arr1 = arr.splice(0, arr.length / 2);
arr.sort(sorter);
arr1.sort(sorter);
return [...arr1, ...arr];
};
console.log(sortInParts(arr));
输出
控制台中的输出将是 −
[
{ id: 3, x: 11 },
{ id: 2, x: 22 },
{ id: 1, x: 33 },
{ id: 6, x: 1 },
{ id: 5, x: 2 },
{ id: 4, x: 3 }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

