-3

Given an array of users, write a function, namesAndRoles that returns all of user's names and roles in a string with each value labeled.

const users = [{
    name: 'Homer',
    role: 'Clerk',
    dob: '12/02/1988',
    admin: false
  },
  {
    name: 'Lisa',
    role: 'Staff',
    dob: '01/30/1965',
    admin: false
  },
  {
    name: 'Marge',
    role: 'Associate',
    dob: '09/10/1980',
    admin: true
  }
];

function namesAndRoles(users) {
  output = "";
  for (var i = 0; i < users.length; i++)
    output += " Name: " + users[i].name + "\n" + " Role: " + users[i].role + "\n";

  return output;

}

console.log(namesAndRoles(users));

I can't seem to get it in a newline. All I keep getting is:

Name: Homer\n Role: Clerk\n Name: Lisa\n Role: Staff\n Name: Marge\n Role: Associate\n

0

2 Answers 2

0

In your code output += " Name: " + users[i].name + "\n" + " Role: " + users[i].role + "\n"; will create a new line for each value. You can rather use array.reduce and in it's accumulator push a string containing the user's information. Then use join with regex new line

const users = [{
    name: 'Homer',
    role: 'Clerk',
    dob: '12/02/1988',
    admin: false
  },
  {
    name: 'Lisa',
    role: 'Staff',
    dob: '01/30/1965',
    admin: false
  },
  {
    name: 'Marge',
    role: 'Associate',
    dob: '09/10/1980',
    admin: true
  }
];

function namesAndRoles(users) {
  return users.reduce((acc, curr) => {
    acc.push(`Name:${curr.name} Role:${curr.role} DOB:${curr.dob}`);
    return acc;
  }, []).join('\n')

}

console.log(namesAndRoles(users));

Sign up to request clarification or add additional context in comments.

1 Comment

Map is a shorter and more understandable method. See my answer fo a vastly simple version. Also \n is not regex
0

You can simplify the script

\n is ignored by HTML. You can EITHER use <br/> or wrap the output as PRE

const users = [{ name: 'Homer', role: 'Clerk', dob: '12/02/1988', admin: false }, { name: 'Lisa', role: 'Staff', dob: '01/30/1965', admin: false }, { name: 'Marge', role: 'Associate', dob: '09/10/1980', admin: true } ];

function namesAndRoles1(users) {
   return users.map(user => `Name: ${user.name}<br/>Role: ${user.role}${user.admin ? " (admin)":""}<br/>`)
   .join('<hr/>');
}

document.getElementById('output1').innerHTML = namesAndRoles1(users);

function namesAndRoles2(users) {
   return users.map(user => `Name: ${user.name}\nRole: ${user.role}${user.admin ? " (admin)":""}\n`)
   .join('\n');
}


document.getElementById('output2').textContent = namesAndRoles2(users);
pre {
    display: block;
    unicode-bidi: embed;
    font-family: monospace;
    white-space: pre;
}
<div id="output1"></div>

<hr/>

<pre id="output2"></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.