Bwizard
Bwizard

Reputation: 1023

Javascript switch array values from boolean to string

I have this 2 dimensional array =

0: (3) [true, false, false]
1: (3) [true, true, false]
2: (3) [true, true, true]
3: (3) [false, false, false]

The position in the array represents the same in each i.e 0 = "Learner" 1 = "Manager", 2 = "ClientAdmin"

I want a new 2 dimensional array that looks like below

0: (3) ["Learner"]
1: (3) ["Learner", "Manager"]
2: (3) ["Learner", "Manager", "ClientAdmin"]
3: (3) []

I have tried

selectedAudienceMandatoryArrayText = []

this.selectedAudienceMandatoryArray.forEach( (isArray, index) => {
          if (isArray[0] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("Learner");
          }
          if (isArray[1] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("Manager");
          }
          if (isArray[2] == true) {
            this.selectedAudienceMandatoryArrayText[index].push("ClientAdmin"); 
          }
        }

but I get the error: Cannot read property 'push' of undefined

What is the most efficient way to do this. ES6 solutions welcome.

Upvotes: 1

Views: 121

Answers (2)

Taplar
Taplar

Reputation: 24965

selectedAudienceMandatoryArrayText = [];

this.selectedAudienceMandatoryArray.forEach(isArray => {
  const roles = [];
  
  if (isArray[0]) roles.push('Learner');
  if (isArray[1]) roles.push('Manager');
  if (isArray[2]) roles.push('ClientAdmin');
  
  selectedAudienceMandatoryArrayText.push(roles);
}

You could push to a new array for each loop, and at the end, push that to the other array. This reduces having to keep track of the index for the outer array.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could check if the flag is set, then take the value from roles with the index or return an empty array.

const
    roles = ["Learner", "Manager", "ClientAdmin"],
    data = [[true, false, false], [true, true, false], [true, true, true], [false, false, false]],
    result = data.map(a => a.flatMap((f, i) => f ? roles[i] : []));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions