Search code examples
javascriptarraysfunctionclosuresjavascript-objects

CLUEDO CHALLENGE: Using a function inside of a function to retrieve a random key of an object inside an array


I'm currently doing a Cluedo challenge in javascript, where I have to generate a random person, with a random weapon who killed the main character. I have an array with different objects of persons, an array with the weapons and an array in what room he might have been killed.

I have to use multiple functions to finish the challenge.

Inside the function: pickMistery, I have to retrieve a random first name, last name, weapon, and room. I have to get the random value from the function randomSelector.

I've tried o create a new array inside random selector, I tried to access variables from the randomSelector in the pickMistery, but ofcourse closure won't let me do that.

var charactersArray = [{firstname: 'Jacob',lastName: "Green", age: 45, description: "He has a lot of connections", occupation: "Entrepreneur"}, {firstname: 'Will',lastName: "Ding", age: 45, description: "Cool guy", occupation: "Scientis"}]

const randomSelector = function(arr) {
    for (var i = 0; i < arr.length; i++) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
};


const pickMistery = function(arr) {
  for (var i = 0; i < arr.length; i++) {
   var firstName = randomSelector(arr[i].firstName);
  }
  return firstName
};

console.log(pickMistery(charactersArray))

What I'm trying to achieve:

  • retrieving the firstName inside this array. :

var charactersArray = [{firstname: 'Jacob',lastName: "Green", age: 45, description: "He has a lot of connections", occupation: "Entrepreneur"}, {firstname: 'Will',lastName: "Ding", age: 45, description: "Cool guy", occupation: "Scientis"}]

I want to retrieve a random firstname from this array, so it would be 'Jacob', Or 'Will'.

Hope I made it clear with this question, this is my first time posting on StackOverflow :)!

This is my codesandbox for this code btw:

https://codesandbox.io/s/7j16l43jnj


Solution

  • This is how you can do it.

    There are some issues you have in your.

    1. Return inside for loop doesen't make sense
    2. You're passing arr[i].firstname as argument to randomSelector function which is a string and than you try character which is not you want.

    var charactersArray = [{firstname: 'Jacob',lastName: "Green", age: 45, description: "He has a lot of connections", occupation: "Entrepreneur"}, {firstname: 'Will',lastName: "Ding", age: 45, description: "Cool guy", occupation: "Scientis"}]
    
    const randomSelector = function(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
    };
    
    
    const pickMistery = function(arr) {
      return randomSelector(arr).firstname
    };
    
    console.log(pickMistery(charactersArray))