1

I am doing a project in JS and Node.js and I need to extract a random element from my array and then display it.

// enemies.js
const enemies = [
  "Wizard Monster",
  "Ice Golem",
  "Electro Dragon",
  "Fire Giant",
  "Rahzar Mutant",
]
export default enemies

// fight.js
import enemies from "../utils/enemies.js"

// Code here

Any ideas ?

Thanks in advance.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
TheVSDev
  • 112
  • 13
  • 1
    What's the specific issue? Have you generated a random 0 <= number < enemies.length? If not, how to do so is searchable, e.g., "javascript generate random number between..." etc. – Dave Newton Jan 27 '23 at 18:49
  • Have you at least tried: `enemies[Math.floor(Math.random() * enemies.length)]`? – Mr. Polywhirl Jan 27 '23 at 18:50
  • "Any ideas?" isn't a suitable question here. Please revise to describe exactly what you're having trouble with. I see no code that would display a value. See [ask]. – isherwood Jan 27 '23 at 18:52

2 Answers2

3

Something like below will give you a random element from the array:

let enemy = enemies[Math.floor(Math.random()* enemies.length)];

Using underscore or lodash is another option:

let enemy = _.sample(enemies);

or

let enemy = enemies[_.random(enemies.length-1)];
0
const enemies = [
  "Wizard Monster",
  "Ice Golem",
  "Electro Dragon",
  "Fire Giant",
  "Rahzar Mutant",
];
const amount_items_array = enemies.length;
const item_sorted = Math.floor(Math.random() * amount_items_array);
enemies.splice(item_sorted, 1)
console.log(enemies);
Leandro Castro
  • 241
  • 2
  • 13
  • 1
    That's... an approach. Seems a bit heavy for the task, and I don't understand why something is called `_sorted` since there's no sorting, or what the intermediate length variable is really useful for. – Dave Newton Jan 27 '23 at 18:54