Filter for sorting in angular js for JSON data

I am new to angular js and have a basic understanding of how filters work in angular js. I am stuck with sorting my jSON data array, as there are various options by which it should be 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" } ] 

Another combination of the same array may be:

 [ { type:0, emp_name:"", connected_on:"9876543210" }, { type:1, emp_name:"xyz", connected_on:"9876543210" }, { type:0, emp_name:"abcd", connected_on:"9876543210" } ] 

Each array will have one object, where type: 1 , will be there, and after sorting it should always be the first element.

After that, the sorted array should have all those elements that have emp_name: "" .

Finally, the sorted array should contain all other elements sorted according to emp_name: "any names"

Thus, the results should look something like this:

 [ { type:1, emp_name:"xyz", connected_on:"9876543210" }, { type:0, emp_name:"", connected_on:"9876543210" }, { type:0, emp_name:"abcd", connected_on:"9876543210" } ] 

Can someone help me write a filter to get the desired result. Thanks in advance. If any other information is required, please let me know.

Also connected_on is a unique value, so I use the track from JSONarr.connected_on

+5
source share
2 answers

The sort function expects -1 , 0 , -1 . -1 means before, 0 means no change, and 1 means later.

Now you need to sort based on 2 parameters, so it is better to have an arithmetic value. Have a higher priority based value. Therefore, in the following situation, we must first sort based on type , and then based on emp_name .

To sort in ascending order, return 1 for larger and -1 for smaller. For a downward return value. Now, combining this for both keys, you 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) 
+2
source

Suppose your array name is emplist. You can find something here. You will get the desired result. Use the table to search for data.

 <input type="text" ng-model="search"> <table> <th>type</th> <th>Emp name</th> <th>connected on</th> <tr ng-repeat="item in emplist|filter:search"> <td>{{item.type}}<td> <td>{{item.emp_name}}<td> <td>{{item.connected_on}}<td> </tr> </table> 
0
source

All Articles