javascriptarrow-functionsfilterfunction

How to filter an array value if it containes some string


I have an array that looks like this

[ { day: 'Friday', time: '14-16 Free' },
 { day: 'Friday', time: '16-18 Free' },
 { day: 'Friday', time: '18-20 Free' },
 { day: 'Friday', time: '20-22 Fully booked' } ]

and I want to filter out any value that doesn't include 'Free' in it, I tried with the length but it didn't work, can somebody explain to me why?

var array = [ { day: 'Friday', time: '14-16 Free' },
     { day: 'Friday', time: '16-18 Free' },
     { day: 'Friday', time: '18-20 Free' },
     { day: 'Friday', time: '20-22 Fully booked' } ];
console.log(array.filter((e) => e.time === (e.time.length < 11)));


Solution

  • Try Array.prototype.indexOf instead:

    let data = [ 
     { day: 'Friday', time: '14-16 Free' },
     { day: 'Friday', time: '16-18 Free' },
     { day: 'Friday', time: '18-20 Free' },
     { day: 'Friday', time: '20-22 Fully booked' }
    ];
    
    let result = data.filter((e) => e.time.indexOf('Free') === -1);
    
    console.log(result); // [{day: "Friday", time: "20-22 Fully booked"}]
    

    The Plunker is here.