如何按预定义值对对象数组进行排序?

ulydmbyx  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(317)

给定以下对象数组:

const arr = [
  {
    "unit": "Room 2",
    "name": "House A"
  },
  {
    "unit": "Room 1",
    "name": "House A"
  },
  {
    "unit": "Main House",
    "name": "House A"
  },
  {
    "unit": "Room 3",
    "name": "House B"
  },
  {
    "unit": "Room 1",
    "name": "House B"
  },
  {
    "unit": "Room 2",
    "name": "House B"
  },
  {
    "unit": "Main House",
    "name": "House B"
  },
]

我想按照以下示例对其进行排序:

[
  { unit: 'Main House', name: 'House A' },
  { unit: 'Room 1', name: 'House A' },
  { unit: 'Room 2', name: 'House A' },
  { unit: 'Main House', name: 'House B' },
  { unit: 'Room 1', name: 'House B' },
  { unit: 'Room 2', name: 'House B' },
  { unit: 'Room 3', name: 'House B' }
]

我可以说把物体移到哪里 unit === 'Main House' 到共享相同名称的其他值的顶部
我尝试下面的方法,但没有用

const result = arr.sort((c1, c2) => (c1.unit === 'Main House' || c2.unit === 'Main House') ? 1 : -1)
csbfibhn

csbfibhn1#

您可以按如下顺序检查条件:

const arr=[{unit:"Room 2",name:"House A"},{unit:"Room 1",name:"House A"},{unit:"Main House",name:"House A"},{unit:"Room 3",name:"House B"},{unit:"Room 1",name:"House B"},{unit:"Room 2",name:"House B"},{unit:"Main House",name:"House B"}];
arr.sort((a, b) => a.name !== b.name ? a.name.localeCompare(b.name) : 
    a.unit === b.unit ? 0 : 
    a.unit === 'Main House' ? -1 : 
    b.unit === 'Main House' ? 1 : a.unit.localeCompare(b.unit))
console.log(arr);
yh2wf1be

yh2wf1be2#

排序 name 首先 unit 第二个例外是 "Main House" 登上顶峰。 String#localeCompare 使排序比较更容易:

const arr = [
  { "unit": "Room 2"    , "name": "House A" },
  { "unit": "Room 1"    , "name": "House A" },
  { "unit": "Main House", "name": "House A" },
  { "unit": "Room 3"    , "name": "House B" },
  { "unit": "Room 1"    , "name": "House B" },
  { "unit": "Room 2"    , "name": "House B" },
  { "unit": "Main House", "name": "House B" },
];

arr.sort((a, b) => {
  const nameOrder = a.name.localeCompare(b.name);
  if (nameOrder !== 0)
    return nameOrder;
  if(a.unit === "Main House")
    return -1;
  if (b.unit === "Main House")
    return 1;
  return a.unit.localeCompare(b.unit);
});

console.log(arr)

可以通过使用逻辑运算符和类型强制来缩短:

const arr = [{ "unit": "Room 2", "name": "House A" }, { "unit": "Room 1", "name": "House A" }, { "unit": "Main House", "name": "House A" },{ "unit": "Room 3", "name": "House B" },{ "unit": "Room 1", "name": "House B" },{ "unit": "Room 2", "name": "House B" },{ "unit": "Main House", "name": "House B" },];

arr.sort((a, b) => 
  a.name.localeCompare(b.name) ||
  ((b.unit === "Main House") - (a.unit === "Main House")) ||
  a.unit.localeCompare(b.unit)
);

console.log(arr);

相关问题