1

I only want to return the socket id, but forEach returns an undefined value, and find returns the entire object.

I only want the output to be 12345.

const users= [
  { host: true, socketId: "12345" },
  { host: false, socketId: "987654" },
  { host: false, socketId: "5678345" },
];

let socketId = users.forEach((user) => {
  if (user.host === true) {
    return user.socketId;
  }
});//this return undefined 

 let socketId = users.find((user) => {
  if (user.host === true) {
    return user.socketId;
  }
});//this return the whole object {host:true,socketId:"12345"}

    const getHostSocketId = () => {
  for (var i = 0; i < users.length; i++) {
    if (users[i].host === true) {
      return users[i].socketId;
    }
  }
};

   let socketId = getHostSocketId(); //This works, but I'd rather use a method like the ones mentioned above.

   console.log(socketId); //i want this to be 12345

2 Answers 2

2
let socketId = users.find(u => u.host)?.socketId
Sign up to request clarification or add additional context in comments.

Comments

1
let answer = (inputArray) => {
    const outputArray = []
    
    inputArray.forEach((element) => {
      if (element.host === true) {
        outputArray.push(element.socketId)
      }
    })

    return JSON.stringify(outputArray, null, '  ')
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.