skip to Main Content

I have a section in which user can filter different data on drop-down select ,

I have an array of data as follows.

const data = [
    {
        name: 'Trump',
        country: 'USA',
        age: 70,
        IQ: 140,
    },
    {
        name: 'ID Amini',
        country: 'Uganda',
        age: 50,
    },
    {
        name: 'Kenyatta',
        country: 'Kenya',
        age: 60,
        
    },
    {
        name: 'Obama',
        country: 'USA',
        age: 45,
        IQ: 141
        
    }
]

My aim is also to be able to get all objects which do not contain IQ as you can see in the above array there are objects which do not contain IQ.

Live demo : demo

Here is what I have tried so far.

let filter = ['empty']; // passed dynamically u can pass eg Obama, kenyata etc etc
let filterTyped ='IQ' // passed dynamically als here u can pass name, country etc etc

let filtredData = filter.forEach((item) =>{
    let dataFilter = data.find((element) =>{
        //return all objects which does not contain IQ if Item is empyt
        if(item === 'empty'){
            return element[filterTyped] ==undefined;
        }
        // return found object
        return element[filterTyped] ==item;
    })

    console.log('Filtred', dataFilter)
    if(!dataFilter) return;
})

Any idea how to solve this issue?

4

Answers


  1. Two ways to achieve this:

    1. Check with the hasOwnProperty method:
    const data = [
      { name: 'Trump', country: 'USA', age: 70, IQ: 140 },
      { name: 'ID Amini', country: 'Uganda', age: 50 },
      { name: 'Kenyatta', country: 'Kenya', age: 60 },
      { name: 'Obama', country: 'USA', age: 45, IQ: 141 }
    ];
    
    const filtered = data.filter((e) => !e.hasOwnProperty('IQ'));
    
    console.log(filtered);
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    1. Check with destructuring:

    Careful with using just IQ and !IQ as a return value, because falsy values like 0 will be false, even though that is a valid value for a field that holds a numeric value.

    const isNumeric = (n) => !isNaN(n - parseFloat(n));
    
    const data = [
      { name: 'Trump', country: 'USA', age: 70, IQ: 150 },
      { name: 'ID Amini', country: 'Uganda', age: 50 },
      { name: 'Kenyatta', country: 'Kenya', age: 60 },
      { name: 'Obama', country: 'USA', age: 45, IQ: 141 },
      { name: 'Foobar', country: 'USA', age: 99, IQ: 0 },
    ];
    
    const noIq = data.filter(({ IQ }) => !isNumeric(IQ));
    console.log(noIq);
    
    const hasIq = data.filter(({ IQ }) => isNumeric(IQ));
    console.log(hasIq);
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    A broken example:

    const isNumeric = (n) => !isNaN(n - parseFloat(n));
    
    const data = [
      { name: 'Trump', country: 'USA', age: 70, IQ: 150 },
      { name: 'ID Amini', country: 'Uganda', age: 50 },
      { name: 'Kenyatta', country: 'Kenya', age: 60 },
      { name: 'Obama', country: 'USA', age: 45, IQ: 141 },
      { name: 'Foobar', country: 'USA', age: 99, IQ: 0 },
    ];
    
    const wrong = data.filter(({ IQ }) => !IQ);
    
    console.log(wrong); // Includes 'Foobar'
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
  2. Referring to your snippet, the error is that forEach does not return the value. Here is a dummy code, ofc you can make it better.

    let filter = ['empty']; // passed dynamically u can pass eg Obama, kenyata etc etc
    let filterTyped ='IQ' // passed dynamically als here u can pass name, country etc etc
    
    let filteredData = [];
    filter.forEach((f) => {
      data.forEach((element) => {
            //return all objects which does not contain IQ if Item is empyt
            if(f === 'empty' && element.IQ === undefined) {
               filteredData.push(element);
            }
        })
    })
    
    console.log(filteredData);
    
    Login or Signup to reply.
  3. Various examples using filter() and hasOwnProperty()

    const data = [
        {
            name: 'Trump',
            country: 'USA',
            age: 70,
            IQ: 140,
        },
        {
            name: 'ID Amini',
            country: 'Uganda',
            age: 50,
        },
        {
            name: 'Kenyatta',
            country: 'Kenya',
            age: 60,
            
        },
        {
            name: 'Obama',
            country: 'USA',
            age: 45,
            IQ: 141
            
        }
    ]
    
    
    function doFilter(filter, filterTyped) {
      return data.filter(r => {
        if (filter[0] === 'empty') {
          if (!r.hasOwnProperty(filterTyped)) { return r }
        } else {
          if (r.hasOwnProperty(filterTyped) &&  filter.includes(r[filterTyped])) { return r }
        }
      })
    }
    
    
    let filter = ['empty']
    let filterTyped ='IQ'
    console.log( doFilter(filter, filterTyped) ) // ID Amini and Kenyatta
    
    filter = [141]
    filterTyped ='IQ'
    console.log( doFilter(filter, filterTyped) ) // Obama
    
    filter = [140, 141]
    filterTyped ='IQ'
    console.log( doFilter(filter, filterTyped) ) // Trump and Obama
    Login or Signup to reply.
  4. Is this what you are looking for?

    const data = [{
        name: 'Trump',
        country: 'USA',
        age: 70,
        IQ: 140,
      },
      {
        name: 'ID Amini',
        country: 'Uganda',
        age: 50,
      },
      {
        name: 'Kenyatta',
        country: 'Kenya',
        age: 60,
    
      },
      {
        name: 'Obama',
        country: 'USA',
        age: 45,
        IQ: 141
    
      }
    ]
    
    let noIQ = [];
    let hasIQ = [];
    
    for (let key = 0; key < data.length; key++) {
      if (!("IQ" in data[key])) {
        noIQ.push(data[key]);
    
        // return single object for each entry
        object = Object.assign({}, ...noIQ)
        console.log("object", object)
      }
    
      if ("IQ" in data[key]) {
        hasIQ.push(data[key])
      }
    }
    
    console.log("noIQ:", noIQ)
    /* console.log("hasIQ:", hasIQ) */
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search