JabbaWook JabbaWook - 5 months ago 10
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:

["red","blue","red","blue","red","red"]


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:

["blue","red","blue","red","blue","blue"]





SOME CONTEXT

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

CURRENT CODE

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

$("#myonoffswitch").on("change",function(d){
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"];
}
else{
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

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

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

console.log(array);

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"));

console.log(array2);

Comments