wyc
wyc

Reputation: 55293

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.

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?

Upvotes: 1

Views: 81

Answers (4)

Vanojx1
Vanojx1

Reputation: 5574

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

Upvotes: 2

greenseed
greenseed

Reputation: 529

This is exactely what you need:

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

As you can see into this post the solution is to check both value inside your sort().

Look at the example on that post!

Upvotes: 1

Andy Dunnings
Andy Dunnings

Reputation: 136

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

Upvotes: 2

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22625

You should return positive value, zero or negative from callback of 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.
     }
})

Upvotes: 1

Related Questions