Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript : Filter list with element contains

I have below object –

[
{
 employeeId:1
 employeeName:"ABC"
},
{
 employeeId:2
 employeeName:"ABD"
},
{
 employeeId:3
 employeeName:"FEW"
},
{
 employeeId:4
 employeeName:"JKABL"
},]

I want to filter this list as per word provided on employeeName.

Eg. If employee name word provided :- AB ; then it should filter out –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
     employeeId:1
     employeeName:"ABC"
    },
    {
     employeeId:2
     employeeName:"ABD"
    },
    {
     employeeId:4
     employeeName:"JKABL"
    },]

As EmployeeIds 1,2 and 4 contains employeename with AB.

For this I tried –

object.filter(x=>x.employeeName.indexOf("AB")>-1)

This is returning empty array every time.

Second way I tried –

   var filteredObject=object.map(x=>{
 if(x.employeeName.indexOf("AB")>-1)
  return x;
});

This is returning undefined every time.

>Solution :

You can define a custom function which filter using includes:

const data = [
  {
    employeeId: 1,
    employeeName: 'ABC',
  },
  {
    employeeId: 2,
    employeeName: 'ABD',
  },
  {
    employeeId: 3,
    employeeName: 'FEW',
  },
  {
    employeeId: 4,
    employeeName: 'JKABL',
  },
];

const filterName = (search) => {
  return data.filter((value) => value.employeeName.includes(search));
};

console.log(filterName('AB'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading