繁体   English   中英

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

[英]How to sort an array of objects by a predefined value?

给定以下对象数组:

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)

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

 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);

首先按name排序,然后按unit排序,但"Main House"除外,会升至顶部。 String#localeCompare使排序比较容易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)

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

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM