排序对象数组离开第一个字段

时间:2019-05-08 14:01:50

标签: javascript

我有一个如下所示的对象数组:

result =
[
   {"id": 1,"Name": "K"},
   {"id": 2,"Name": "I"},
   {"id": 3,"Name": "A"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 6,"Name": "B"}
]

我按照下面的字母顺序对对象数组进行排序

result.sort(function(a, b) {
      return a.Name.localeCompare(b.Name);
   });

但是我想对离开我的第一个对象即K的对象进行排序

我希望我的数组看起来像

[
   {"id": 1,"Name": "K"},
   {"id": 3,"Name": "A"},
   {"id": 6,"Name": "B"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 2,"Name": "I"}
]

如何实现?

8 个答案:

答案 0 :(得分:6)

基本上,您要提取第一个元素,对数组进行排序,然后使用destructuring assignments再次添加。

const [first, ...rest] = [
   {"id": 1,"Name": "K"},
   {"id": 2,"Name": "I"},
   {"id": 3,"Name": "A"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 6,"Name": "B"}
];

const result = [first, ...rest.sort((a, b) => a.Name.localeCompare(b.Name))];
console.log(result);

答案 1 :(得分:1)

let first = results.shift()
results.sort()
results.unshift(first)

答案 2 :(得分:0)

您可以使用slice()

[
   {"id": 1,"Name": "K"},
   {"id": 3,"Name": "A"},
   {"id": 6,"Name": "B"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 2,"Name": "I"}
].slice(1);

答案 3 :(得分:0)

    var result =
        [
            {"id": 1,"Name": "K"},
            {"id": 2,"Name": "I"},
            {"id": 3,"Name": "A"},
            {"id": 4,"Name": "C"},
            {"id": 5,"Name": "G"},
            {"id": 6,"Name": "B"}
        ]

    var firstObj=result.shift();

    result.sort(function(a, b) {
        return a.Name.localeCompare(b.Name);
    });
    result.unshift(firstObj);

答案 4 :(得分:0)

您可以将shiftunshiftsort一起使用。

let firstItem = result.shift();
result.sort(function(a, b) {
  return a.Name.localeCompare(b.Name);
});
result.unshift(firstItem)

班次:

删除数组的第一项并返回它。

取消变速

将项目放置在数组的开头。

答案 5 :(得分:0)


const result = [
   {"id": 1,"Name": "K"},
   {"id": 2,"Name": "I"},
   {"id": 3,"Name": "A"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 6,"Name": "B"}
]

const firstElement = result.shift();
result.sort((a, b) => a.Name.localeCompare(b.Name));
result.unshift(firstElement);

答案 6 :(得分:0)

您可以像这样使用Array.slice()Spread Operator

result =
[
   {"id": 1,"Name": "K"},
   {"id": 2,"Name": "I"},
   {"id": 3,"Name": "A"},
   {"id": 4,"Name": "C"},
   {"id": 5,"Name": "G"},
   {"id": 6,"Name": "B"}
]

result = [
  result.slice(0, 1),
  ...result.slice(1).sort((a, b) => a.Name.localeCompare(b.Name))
]

console.log(result);

答案 7 :(得分:0)

您可以存储第一项并检查参数(如果值是第一项)。该项目首先被排序,然后所有其他元素都被排序。

这种方法保留给定数组的相同对象引用。

var result = [{ id: 1, Name: "K" }, { id: 2, Name: "I" }, { id: 3, Name: "A" }, { id: 4, Name: "C" }, { id: 5, Name: "G" }, { id: 6, Name: "B" }],
    first = result[0];    

result.sort(function(a, b) {
    return (b === first) - (a === first) || a.Name.localeCompare(b.Name);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }