How do I make this structure:
busy: admin1,admin2,admin3,
sleep: admin0,
I don’t know what I’m doing wrong, I need to line it all up
const user = [ { status: "busy", username: "admin1"}, { status: "busy", username: "admin2"}, { status: "busy", username: "admin3"}, { status: "sleep", username: "admin0"}, ] let text = `` user.map((v) => { text += `${v.status}: ${v.username}\n` }) console.log(text)
busy: admin1 busy: admin2 busy: admin3 sleep: admin0
I need to do it correctly, how?
I don’t know what I should do next I’m up>Solution :
You could group them first (use
array.reduce
) and then create the texts from there.const user = [{ status: "busy", username: "admin1" }, { status: "busy", username: "admin2" }, { status: "busy", username: "admin3" }, { status: "sleep", username: "admin0" }, ] const grouped = user.reduce((groups, user) => ({ ...groups, [user.status]: [...(groups[user.status] || []), user.username] }), {}); const text = Object.entries(grouped).map(([key, values]) => `${key}: ${values}`).join('\n'); console.log(text);