1

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?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

4 Answers4

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

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);
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
  • You should return [positive, zero or negative value from callback](http://www.w3schools.com/jsref/jsref_sort.asp). Your solution would work because of automatic type conversion, but it's not the best practice. – Krzysztof Atłasik Aug 16 '16 at 07:23
  • I'll edit my answer based on your suggestion... thanks – Vanojx1 Aug 16 '16 at 07:30
  • I came out with this: `objPanoramas.sort((a, b) => { if (a.isDefault !== b.isDefault) { return a.isDefault < b.isDefault } return a.name > b.name })` Does it do the same as your code? – alexchenco Aug 16 '16 at 07:30
  • basically yes, but as suggested by @yariash compare the strings using the proper comparison function – Vanojx1 Aug 16 '16 at 07:36
1

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.
     }
})
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
1

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!

Community
  • 1
  • 1
greenseed
  • 509
  • 5
  • 10