Vijay Kumar
Vijay Kumar

Reputation: 75

How to filter JSON data using Typescript / Javascript / Angular 4?

I have json data like this

data :[
{taskname:'chennai',    id:'maa' }
{taskname:'mumbai',     id:'bom' }
{taskname:'delhi',      id:'del' }
....
....
....
{taskname:'salem',      id:'che'}
{taskname:'bengaluru',  id:'blr'}
{taskname:'chavvapet',  id:'chv'}
}]

now i need to filter this data and return matching values (just like autocomplete). For example when i get value CH , first i need to check on ID and then on taskname. so the return value should be like this. must order ID matching top and then taksname matching.

{taskname:'salem',      id:'che'}
{taskname:'chavvapet',  id:'chv'}
{taskname:'chennai',    id:'maa'}

Incase if i get value CHE, then i need to return value like this

{taskname:'salem',      id:'che'  }
{taskname:'chennai',    id:'maa'  }

Could someone please tell me how to do filter using typescript ?

Tried few of this answer, but no luck.

Upvotes: 2

Views: 24893

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8481

Try this code

const data = [
{taskname:'chennai',  id:'maa',status:'Submitted'},
{taskname:'mumbai',   id:'bom',status:'Resolved'},
{taskname:'delhi',    id:'del',status:'Submitted'},
{taskname:'salem',    id:'che',status:'In Progress'},
{taskname:'bengaluru',id:'blr',status:'Resolved'},
{taskname:'chavvapet',id:'chv',status:'Submitted'}
];

function filterByString(data, s) {
   return data.filter(e => e.id.includes(s) || e.taskname.includes(s))
       .sort((a,b) => a.id.includes(s) && !b.id.includes(s) ? -1 : b.id.includes(s) && !a.id.includes(s) ? 1 :0);
}

console.log(filterByString(data, "ch"));

Upvotes: 6

Related Questions