Brownman Revival Brownman Revival - 4 months ago 10
jQuery Question

How to make empty data go last in sort jquery



var data = [{
"id": "2"
}, {
"id": "3"
}, {
"id": "4"
}, {
"id": "5"
}, {
"id": "6"
}, {
"id": "7"
}, {
"id": "1"
}, {
"id": ""
}, {
"id": ""
}, {
"id": ""
}]

$('.up').click(function() {
var prop = $(this).closest('th').attr('data-name');
var data1 = sortResults(data, prop, 'asc')
console.log(data1)
})
$('.down').click(function() {
var prop = $(this).closest('th').attr('data-name');
var data1 = sortResults(data, prop, 'desc')
console.log(data1)
})


function sortResults(data, prop, asc) {
console.log("done data " + data)
console.log("done prop " + prop)
console.log("done asc " + asc)
data = data.sort(function(a, b) {
if (asc)
return (a[prop] > b[prop]);
else
return (b[prop] > a[prop]);
});

return data;
}

.up {
display: block;
height: 10px;
width: 15px;
background-repeat: no-repeat;
background-color: blue;
cursor: pointer;
}
.down {
display: block;
height: 10px;
width: 15px;
background-repeat: no-repeat;
background-color: red;
cursor: pointer;
}
.filter {
display: inline-block;
height: 14px;
width: 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
<tr>
<th data-name='id'>ID <span class='filter'><span class='up'></span><span class='down'></span></span>
</th>
</tr>
</table>






  1. How to make id with empty value value go last from
    .sort()


Answer

Your sort callback is incorrect. It needs to return a negative number if the first item goes before the second, a positive number if the second goes before the first, or 0 if they're "the same." Instead, your function is returning booleans, which will get coerced to 1 (if true) or 0 (if false), which won't sort things correctly.

String#localeCompare is handy for sorting strings. It will consider "" "earlier" than anything with content, though, so we have to special-case that:

function sortResults(data, prop, asc) {
  data.sort(function(a, b) {
    var vala = a[prop],
        valb = b[prop];
    if (!vala) {
        // vala is blank -- if valb is also blank, return 0;
        // otherwise, return 1 to put vala *after* valb
        return !valb ? 0 : 1;
    }
    if (!valb) {
        // valb is blank, return -1 to put it *after* vala
        return -1;
    }
    if (asc) {
      // Ascending sort, use localeCompare
      return vala.localeCompare(valb);
    }
    // Descending sort, use localeCompare the other way around
    return valb.localeCompare(vala);
  });

  return data;
}

Side note: Array#sort sorts the array in place, so no need for data = data.sort(...).