I am new to angular js and have basic understanding of how filters work in angular js.I am stuck to sort my jSON data array as there are various parameters on which it has to get sorted.
My JSON array is in this format:
[
{
type:0,
emp_name:"xyz",
connected_on:"9876543210"
},
{
type:1,
emp_name:"",
connected_on:"9876543210"
},
{
type:1,
emp_name:"abcd",
connected_on:"9876543210"
},
{
type:0,
emp_name:"pqr",
connected_on:"9876543210"
}
]
Other combination of the same array can be:
[
{
type:0,
emp_name:"",
connected_on:"9876543210"
},
{
type:1,
emp_name:"xyz",
connected_on:"9876543210"
},
{
type:0,
emp_name:"abcd",
connected_on:"9876543210"
}
]
Every array will have any one object where type:1 , will be there and after sorting it has to be the first element always.
After that,the sorted array should have all those elements whose emp_name:"" is there.
At last of the sorted array it should contain all the remaining elements sorted according to emp_name:"whatever names"
So the results should look something like this below:
[
{
type:1,
emp_name:"xyz",
connected_on:"9876543210"
},
{
type:0,
emp_name:"",
connected_on:"9876543210"
},
{
type:0,
emp_name:"abcd",
connected_on:"9876543210"
}
]
Can anyone help me to write the filter to get the desired result.Thanks in advance.If any other info required please let me know.
Also connected_on is unique value so i am using track by JSONarr.connected_on
Sort function expect -1
, 0
, -1
as result. -1
means before, 0 means no change and 1 means later.
Now you have to sort based on 2 parameters, so its better to have an arithmetic value. Have higher value based on priority. So in following situation, we have to sort first based on type
and then based on emp_name
.
To sort ascending, return 1 for greater and -1 for smaller. For descending reverse the values. Now combining this for both keys you will get something like this:
var data=[{type:0,emp_name:"xyz",connected_on:"9876543210"},{type:1,emp_name:"",connected_on:"9876543210"},{type:1,emp_name:"abcd",connected_on:"9876543210"},{type:0,emp_name:"pqr",connected_on:"9876543210"}];
data.sort(function(a, b) {
var _a = a.type > b.type ? -10 : a.type < b.type ? 10 : 0;
var _b = a.emp_name > b.emp_name ? 1 : a.emp_name < b.emp_name ? -1 : 0;
return _a + _b;
});
console.log(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With