简体   繁体   English

如何基于布尔属性和名称属性对数组进行排序?

[英]How to sort an array based on a boolean prop and a name prop?

I have an array of objects that look like this: 我有一个看起来像这样的对象数组:

[
  {
    name: s1,
    isDefault: false
  },
  {
    name: s2,
    isDefault: true
  },
  {
    name: s3,
    isDefault: false
  }
]

I want to sort this array so that the element with isDefault: true is placed first, and have the rest follow this object in alphabetical order. 我想对该数组进行排序,以便将具有isDefault: true的元素放在第一位,让其余元素按照字母顺序跟随此对象。

In other words: 换一种说法:

[
  {
    name: s2,
    isDefault: true
  },
  {
    name: s1,
    isDefault: false
  },
  {
    name: s3,
    isDefault: false
  }
]

I know how to accomplish the first condition: 我知道如何完成第一个条件:

objPanoramas.sort((a, b) => {
  return a.isDefault < b.isDefault
})

How can I integrate the second condition? 如何整合第二个条件?

objPanoramas.sort((a, b) => {
  if (a.isDefault == b.isDefault) {
    name1 = a.name;
    name2 = b.name;
    return name1<name2?-1:(name1>name2?1:0)
  }
  return a.isDefault < b.isDefault
})

try this 尝试这个

 objPanoramas = [{ name: "s1", isDefault: false },{ name: "s1", isDefault: true }, { name: "s2", isDefault: true }, { name: "s3", isDefault: false }] objPanoramas.sort((a, b) => { if ((a.isDefault && b.isDefault) || (!a.isDefault && !b.isDefault)) { return a.name.localeCompare(b.name) }else{ return !a.isDefault } }) console.log(objPanoramas); 

You should return positive value, zero or negative from callback of sort : 您应该从sort的回调中返回正值,零或负值:

objPanoramas.sort((a, b) => {
     if(a.isDefault == b.isDefault) {
         return a.name.localeCompare(b.name); //in case both values are equal do alphabetical sort
     } else if(a.isDefault) {
          return 1; //else if a.isDefault is true return positive value.
     }
})

This is exactely what you need: 这正是您所需要的:

https://stackoverflow.com/a/4576720/6482090 https://stackoverflow.com/a/4576720/6482090

As you can see into this post the solution is to check both value inside your sort(). 正如您在这篇文章中看到的,解决方案是检查sort()中的两个值。

Look at the example on that post! 看那个帖子上的例子!

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

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