i have the following array
"data": {
"risks": [
{
"id": "22",
"name": true,
"surname": 0.5,
"age": 0.75,
"heigth": 50,
"num1": [],
"num2": []
},
{
"id": "55",
"name": true,
"surname": 0.5,
"age": 0.75,
"heigth": 50,
"num1": [],
"num2": []
},
{
"id": "33",
"name": true,
"surname": 0.5,
"age": 0.75,
"heigth": 50,
"num1": [1,2,3,4,5],
"num2": [4,5,6,9]
}
]}
is there a way to sort the array so the objects with empty num1 OR num2 to be last on the array ? i tried something like the following but it didnt work.
array.sort((x, y) => !!y.num1.length ==0- !!x.num1.length ==0|| !!y.num2.length ==0- !!x.num2.length ==0);
2
Answers
You need to return an integer from the
sort()
method you implemented. Either0
or> 0
or< 0
depending on the outcome of your comparison.One of the simplest ways to check that at least
num1
ornum2
in any of your objects contains an entity is to sum their lengths and compare, something like this:Note that this approach is assuming that the arrays in the objects are always empty, never
null
.You could take the delta of the negated length for sorting empty arrays to bottom.