Sort JSON alphabetically (with empty value)

I have JSON formatted like this:

account = [
     {"name":"Los Angeles", "country":"USA"},
     {"name":"Boston", "country":"USA"},
     {"name":"", "country":"USA"},
     {"name":"Chicago", "country":"USA"}
]

      

I am trying to sort this alphabetically AZ BY NAME with empty name values.

I tried this, but this kind of AZ with empty values ​​at first.

account.sort( function( a, b ) {
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});

      

+2


source to share


3 answers


account.sort( function( a, b ) {
    if(a.name === "") {
       return 1;
    } else if(b.name === "") {
       return -1;
    } else {
         return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
    }
});

      

In the case of strings, empty strings are considered the smallest value, therefore, sorted as the first element in the array.

However, we need to change the default behavior as per our requirement, so we need to add additional logic for it.



Now when sorting, when we return -1, it means the order is in order and as desired. When we return 1, it means that the order is reversed and needs to be reversed, and when we return 0, both objects / values ​​are the same and no action is required.

Now, in our case, we need to move blank lines to the last one. Hence, if the first object / value is an empty string, swap it and move it to the right in the array. And when the second object / value is an empty string, no action is required as it requires them to be finally.

Hence, this is how things work.

+5


source


You need more suggestions to check for blank lines.



account = [{
  "name": "Los Angeles",
  "country": "USA"
}, {
  "name": "Boston",
  "country": "USA"
}, {
  "name": "",
  "country": "USA"
}, {
  "name": "Chicago",
  "country": "USA"
}]
account.sort(function(a, b) {
  if (b.name.length == 0) {
    return -1;
  }
  if (a.name.length == 0) {
    return 1;
  }
  return a.city.localeCompare(b.city);
});
console.log(account)
      

Run codeHide result


+4


source


No need for additional ifs.

account = [
     {"name":"Los Angeles", "country":"USA"},
     {"name":"Boston", "country":"USA"},
     {"name":"", "country":"USA"},
     {"name":"Chicago", "country":"USA"}
]

account.sort(function(a, b) {
  return (a.name || "zzz").localeCompare(b.name || "zzz");
});

document.write("<pre>" + JSON.stringify(account,null,3))
      

Run codeHide result


a.name || "zzz"

means "if a.name is not empty, use it, otherwise use something" greater "than any name."

+3


source







All Articles