0

I have an array named var_name

How to check in an array if there is an element other than detected

but if my array does not contain detected

and contains different element, it shouldn't do anything. For instance:

  1. var_name = [detected, nondetected] it should execute <div> Do something </div>
  2. var_name = [nondetected, inprogress] it should execute <div> Do nothing </div>
  3. var_name = [detected, detected] it should execute <div> Do nothing </div>

Things tried so far:

!var_name.includes('detected') ? (<div>Do something</div>) : (<div>Do nothing</div>) 

but it fails for my usecase

So in order to do something, there needs to be at-most 1 instance of detected followed by other elements (like nondetected, etc). If it contains all detected, then still it doesn't do anything. How to execute such that?

3
  • based on the 3 cases that you have, how about do a for loop to count how many detected are there? or use filter and get the length of the filtered array? if === 1 then do something, else do nothing Commented Apr 7, 2021 at 23:07
  • How can I do that? Is there a way to use if-else in return function? Commented Apr 7, 2021 at 23:15
  • Do a first pass over the array and reduce it into a count of "detected", then loop it normally to map to JSX and render what you need. Commented Apr 7, 2021 at 23:23

2 Answers 2

1

You might want to refine the "matching" functionality, I just use === 'detected' so it's easier to understand.. but this should get you started:

const var_name = ['detected', 'detected'];
console.log(var_name.filter((item) => item === 'detected').length);

so you can do something like:

var_name.filter((item) => item === 'detected').length === 1 ? do something : do nothing
Sign up to request clarification or add additional context in comments.

2 Comments

Does var_name.filter((item) => item === 'detected').length count the number of instances of 'detected' ?
@SMahajan yes.. but as I said, you might want to refine it
1
const var_name = ["detected", "nondetected", "nondetected", "detected"];
(var_name.filter(x => x == "detected").length === 1) ? console.log("something") : console.log("nothing");

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.