0

I have a data array that I want to filter based on if set variables are set to true or false. I want to write my code in a single function using operators (if possible) instead of having to code for every combination. My data sample looks like this:

chardata = [
     {
    "CharName": "Char1",
     "Magic": TRUE,
     "Melee": TRUE,
     "Ranged": TRUE
    },{
     "CharName": "Char2",
     "Magic": TRUE,
     "Melee": FALSE,
     "Ranged": FALSE
    },{
    "CharName": "Char3",
     "Magic": FALSE,
     "Melee": FALSE,
     "Ranged": TRUE
    }
]

I would like the filter to return Char1 whenever Magic and Ranged are set to true, but not return Char2 or Char3.

const filter = chardata.filter(function (ef) {
      return Magic === true ? 
      ef["Magic"] === true : "",
      Ranged === true ? 
      ef["Melee"] === true : "",
      Melee === true ? 
      ef["Ranged"] === true : ""})

Is is possible to make this work using this method or are are more than one functions needed?

Thanks

1 Answer 1

2

The main issue making a clean solution difficult is your Magic and Range variables, which are standalone instead of being in an easier to manage structure like an object.

Consolidate them into an object. Eg instead of

Magic = true;
Melee = false;
Ranged = true;

have

charType = {
  Magic: true,
  Melee: false,
  Ranged: true
}

Then you can do:

const filter = chardata.filter((oneChar) => {
  return Object.entries(charType)
    .filter(entry => entry[1])
    .every(([key, value]) => oneChar[key] === value);
});

Live demo:

chardata = [
     {
    "CharName": "Char1",
     "Magic": true,
     "Melee": true,
     "Ranged": true
    },{
     "CharName": "Char2",
     "Magic": true,
     "Melee": false,
     "Ranged": false
    },{
    "CharName": "Char3",
     "Magic": false,
     "Melee": false,
     "Ranged": true
    }
]

const charType = {
  Magic: true,
  Melee: false,
  Ranged: true
};


const filter = chardata.filter((oneChar) => {
  return Object.entries(charType)
    .filter(entry => entry[1])
    .every(([key, value]) => oneChar[key] === value);
});

console.log(filter);
strict mode

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.