0

I am trying to assign a color blue for these values of i: 3,4,22,24

right now my code is as follows

JS(paste0('function(z, i) { return i > 2 && i <  5 || i > 21 && i < 24   ? "blue" : "grey"; }'))

Is there a way to accomplish the same using in operator , something like

JS(paste0('function(z, i) { return i in(3,4,22,23)   ? "blue" : "grey"; }'))

Thanks in advance.

1
  • No. That's not how in works. Commented Mar 16, 2017 at 21:56

4 Answers 4

1

Yes. This way:

JS(paste0('function(z, i) { return [3,4,22,23].indexOf(i) > -1  ? "blue" : "grey"; }'))
Sign up to request clarification or add additional context in comments.

2 Comments

[].includes() would look more elegant
it's an option also
0

You can use Array.prototype.indexOf() to see if an item is a in an array. This will give -1 if the item is not in the array, or the index if it's found. Using the ~ bitshift operator we are shifting the binary -1 forward to represent false if the item is not in the given array.

function JSpaste0(z, i) { return ~[3,4,22,23].indexOf(i)  ? "blue" : "grey"; }

console.log(
  JSpaste0(null, 4), // blue
  JSpaste0(null, 66) // grey
)

Comments

0

Yes, you could use in operator with an appropriate object.

JS(paste0('function(z, i) { return i in { 3: 1, 4: 1, 22: 1, 23: 1 } "blue" : "grey"; }'))

Comments

0

Solution 1 - I'd like to state that this is not supported by Internet Explorer or Opera, However it is compatible with all other popular browsers. Check MDN for further details regarding compatibility.

JS(paste0('function(z, i) { return [3,4,22,23].includes(i) ? "blue" : "grey"; }'))

solution 2 -

JS(paste0('function(z, i) { return [3,4,22,23].indexOf(i) > -1  ? "blue" : "grey"; }'))

1 Comment

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.