Search code examples
javascriptjavascript-objects

Javascript Return Conditionals


   searchList(array, filters) { 
      var currentUserId = 125;
      var list = array;  
      // array example [{aisle: A9, userid: 125},{aisle: B2, userid: null},{aisle: C#, userid: 125}] 
      // filters example {assignedButtonActive: true, unassignedButtonActive: false, aisle: A9}
      
      result = Object.keys(list)
        .map((key) => {
          return { ...list[key] };
        })
        .filter((data) => {
          // If assigned or unassigned buttons are not active, this filter doesnt apply and aisle should be the only thing filtering
          let assigned = filters.assignedButtonActive
          let unassigned = filters.unassignedButtonActive
          let aisleSelection = filter.aisle;
          let aisle = data.aisle;
          let userid = data.userid;

          return aisle.indexOf(aisleSelection) > -1 // Need a conditional to also filter out assigned/unassigned if the buttons are active, otherwise not needed.
        });

      return result;
    }

I am trying to filter a list with the combination of an input search and button/flags. I have no problem with the input search function filtering and returning the list. The problem Im having is using boolean flags along with the search input to be even more exact on what i want to filter, but I am having an issue on how to return the result using conditionals/booleans in this case. I cant seem to mix the two conditions for a return with both filters applied. I've tried something like this return aisle.indexOf(aisleSelection) > -1 && (assigned) ? assignedTo == currentUserId : (unassigned) ? assignedTo == null : [] but seems I'm way off. For example if either assigned/unassigned flags are active, it will add one of these two filters assignedTo === currentUserId or assignedTo == null to filter along with aisle filter as well, pretty much so they can work together as well, not one or the other

Not looking for the solution written out for me, more on how I can handle this filtering beyond just an input, with the possibility to off more filters being used

Any help/tips would be greatly appreciated


Solution

  • Finish out the function before returning, then have different return statements for each condition rather than

    return aisle.indexOf(aisleSelection) > -1
    

    try

    if (aisle.indexOf(aisleSelection) > -1) {
    return true} 
    else if (other possibility){
    return true} 
    else (case to filter out){
    return false}
    

    filter gets called on each element in the array, and decides to keep the element if the callback function returns true