Pick a Number from an Array of Int

Hi All,

Could someone help with what is probably a simple bit of code, i’m struggling to figure out the areas with //

var myArray = [1,2,3,4]; //Setting the array.

    if(selectedIndexCount == 1) {
      // Pick Number 2,3 or 4 from myArray
    } else if (selectedIndexCount == 2) {
      // Pick Number 1,3 or 4 from myArray
    } else if (selectedIndexCount == 3) {
      // Pick Number 1,2 or 4 from myArray
    } else if (selectedIndexCount == 4) {
      // Pick Number 1,2 or 3 from myArray
    }

Hi @JBird20,

I’m assuming selectedIndexCount is already being set somewhere earlier in your script?

Here’s a complete, streamlined solution which works for me. It uses underscore syntax to reduce the amount of repetition that you might otherwise need:

var selectedIndexCount = 1; // I'm setting this manually to help me test!
var myArray = [1,2,3,4]; // Setting the array.

var arrayWithoutSelectedIndex = _.without(myArray, selectedIndexCount); // remove selectedIndex from array
console.log(arrayWithoutSelectedIndex); // If selectedIndexCount is 1, then this will output [2, 3, 4]

var pickedNumber = _.sample(arrayWithoutSelectedIndex); // randomly pick one of the remaining values
console.log(pickedNumber); // If selectedIndexCount is 1, this will randomly be set to 2, 3 or 4
3 Likes

hey @neilstudd ,

1000% times better than this mess i was going to use:

if(selectedIndexCount == 12) {
        const setChoice = myArray.slice(1,2,3);
    } else if (selectedIndexCount == 13) {
        const setChoice = myArray.slice(0,1,2)
    } else if (selectedIndexCount == 14) {
        const setChoice = myArray.slice(0,1,3);
    } else if (selectedIndexCount == 15) {
        const setChoice = myArray.slice(0,1,2);
    }

Glad it helped! That’s part of the fun of coding - writing a solution which works (which your version would have, assuming you were then going to randomly select a value from setChoice) and then looking for ways to refactor it to make it more readable / less repetitive.

It’s worth bookmarking the documentation for the underscore syntax as it has loads of useful little helpers that can dig you out of problems like this :slight_smile:

2 Likes

Javascript is a beautiful language for playing with objects and arrays , see lodash library and array prototypes it will have easy methods available for you