0

So I want to filter an array of objects according to a few filters I have created:

items.filter(
    (obj) =>
    (!status || (obj.globalId && obj.globalId !== "")) &&
    (!deletedSwitch || obj.deleted === deletedSwitch) &&
    (!filteredUsername || obj.userId === userId) &&
    (!filteredType || obj.type === filteredType) &&
    (!filteredVariety || obj.variety === filteredVariety) &&
    (!filteredSize || parseInt(obj.size) === filteredSize)
)

So as you can see, I filter the items based on a few properties. These properties are selected through a <select> component. status property used to be a boolean state where I want to check if the item has a globalId or not. However, now I want to change it in a way where I check if status is connected, then I want to filter all items that have a globalId each. But if the status is not connected, I want to filter all items that DO NOT have a globalId. How can I modify my code above to achieve this?

1
  • 3
    Please post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Oct 27, 2022 at 7:44

2 Answers 2

1

Just add it with OR?

items.filter(obj =>
    ((status === "connected" && obj.globalId && obj.globalId !== "") ||
     (status === "not connected" && !obj.globalId)) &&
    (!deletedSwitch || obj.deleted === deletedSwitch) &&
    (!filteredUsername || obj.userId === userId) &&
    (!filteredType || obj.type === filteredType) &&
    (!filteredVariety || obj.variety === filteredVariety) &&
    (!filteredSize || parseInt(obj.size) === filteredSize)
Sign up to request clarification or add additional context in comments.

Comments

0

How about using a ternary (conditional expression)?

(status == "connected" ?
 object.globalId && obj.globalId !== "" :
 !object.globalId)

Or, if you anticipate having more status values in the future, using an object is more extensible (and it's arguably more readable in any case):

({
    "connected": object.globalId && obj.globalId !== "",
    "not connected": !object.globalId,
}[status])

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.