0

I'm trying to make a search engine for my database. I start with mapping all the elements and then I have a filter for some of the things in each elements like this:

const filteredCars = (carsGet.filter(item => {
        const filter = (item.make.toLowerCase().includes(searchfield.toLowerCase()) ||
            item.make.toLowerCase().includes(searchfield.toLowerCase()) === '')
            && (item.year > min || min === '') 
            && (item.year < max || max === '')
            && (item.color === color || color === '');
        console.log(filter);
        return filter
        
        }))

The filter works fine as long as it's just one item, but as soon as I send an array to color it returns false, if I set initialState to color: [] and change color === '' to color === [] they return false from start.

I have created a handler for the color:

handleChange (e) {
    var options = e.target.options;
    
    var value = [];
    for (var i = 0, l = options.length; i < l; i++) {
      if (options[i].selected) {
        value.push(options[i].value);
      }
    }
    console.log(value)
    this.setState({color: value});
  }

The console.log returns ["guld", "red"] but the filter returns false for all elements even if i only select one color

1 Answer 1

1

You can check if color is an array or a string and return a boolean accordingly.

const filteredCars = (carsGet.filter(item => {
    const checkColor = () => {
        if(Array.isArray(color)) {
            return (color.length === 0) || color.includes(item.color);
        } else {
            return (color === '') || (color === item.color);
        }
    }

    const filter = (item.make.toLowerCase().includes(searchfield.toLowerCase()) ||
        item.make.toLowerCase().includes(searchfield.toLowerCase()) === '')
        && (item.year > min || min === '')
        && (item.year < max || max === '')
        && checkColor();
    console.log(filter);
    return filter

}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.