JabbaWook JabbaWook - 1 year ago 93
Javascript Question

"toggle" between 2 values in array - JS

If I have an array containing an order of variables, lets use 2 colors for example:


Is there a built-in function or well known method to "invert" the colors to the other color, so you end up with the result:



So I have 3 arrays, one of colors like the above example, one with html ID's which looks like
and another with cell references in them looking like
. I want to be able to "toggle" these variables in each array, as explained in the example above.


At the minute I just have an event handler that hard codes the changes as such:

team = (team =="blue")? "red" : "blue" ;
if (team =="blue"){
divRange = ["blueBan1","redBan1","bluePick1","redPick1","redPick2","bluePick2","bluePick3","redBan2","blueBan2","redPick3","redPick4","bluePick4","bluePick5","redPick5"];
cellRange = ["B12","D12","B2","D2","D3","B3","B4","D13","B13","D4","D5","B5","B6","D6"];
divRange = ["redBan1","blueBan1","redPick1","bluePick1","bluePick2","redPick2","redPick3","blueBan2","redBan2","bluePick3","bluePick4","redPick4","redPick5","bluePick5"]
cellRange = ["D12","B12","D2","B2","B3","D3","D4","B13","D13","B4","B5","D5","D6","B6"];

Answer Source

var array = ["red","blue","red","red","blue","red","blue"];

array = array.map( colour => colour === "red" ? "blue" : "red");


If you have IDs after the colours, as you requested :

var array2 = ["red05","blue123","red85","red741","blue456","red789","blue320"];

array2 = array2.map( colour => colour.indexOf("red") > -1 ? colour.replace("red","blue") : colour.replace("blue","red"));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download