0

Wasn't sure how to title what I'm looking for properly so I'll try and explain

I have a function

function cat(name, job, height){
 console.log(name);
}

and I'm trying to randomise the 3 variables using the following code

let Array = ['jim, cook, 5','nick, dog, 2'];
const RandomMake = Math.floor(Math.random() * Array.length);
let Random = Array[RandomMake];

so say Random output's jim, cook, 5 i'd like to use those variables within my function.

cat(Random);

Obviously I'm not making a cat generator but it explains what I need. I can't randomise each individual value it must be the group of items (name job height). I'm not sure if this is possible or if i'm just forgetting about a function that will allow me to do this. But it's definitely puzzled me... Thanks in advance for the help :) Always learning.

1 Answer 1

3

You can split the randomly selected string by , and spread the result into the call of cat:

function cat(name, job, height){
 console.log(name);
}
const arr = ['jim, cook, 5','nick, dog, 2'];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomItem = arr[randomIndex];
cat(...randomItem.split(', '));

But, if possible, it would make a bit better organizational sense to have array of objects rather than an array of strings:

function cat({ name, job, height }){
 console.log(name);
}
const arr = [{
  name: 'jim',
  job: 'cook',
  height: 5
}, {
  name: 'nick',
  job: 'dog',
  height: 2,
}];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomItem = arr[randomIndex];
cat(randomItem);

Also, you should avoid declaring a variable named Array - this will shadow the global window.Array, which could easily cause problems. Best to give the variable a different name, like arr.

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

2 Comments

Yeah, awesome thanks! I'm working with an automated api so it's proven easier just to paste in strings instead of making an array of objects. And yea I should've picked up on that before posting haha that was only an example :) I'll Accept in 5 min (need to wait for the cool down)
Sure, if you have to write out a whole lot of things, I can understand using strings. If you need to go that route, you could make things even easier (syntactically) by using a multi-line template literal that you then split by newlines to create the random array. It'll be a bit less mistake-prone than something like ['jim, cook, 5','nick, dog, 2'] with a lot of items.

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.