Home > database >  How do i get the X number of unique items from an array
How do i get the X number of unique items from an array

Time:11-13

Im trying to change the X number in the for loop based on what array this function is using. The function gets x random values from an array which he then checks if it isnt the same value and if it isnt the same value he then returns the 2 random values in the array. i tried doing a switch statement like this:

switch(this) {
   case array1:
       x = 2;
       break;
   case array2:
       x = 3;
       break;
}

code

Array.prototype.random = function () {
    let result = [];
    let bool = false;
    let x = 0;
    for (var i = 0; i < x; i  ) {
        result.push(this[Math.floor(Math.random() * this.length)]);
    }
    while (bool == false) {
        if (result[0] === result[1]) {
            result.pop();
            result.push(this[Math.floor(Math.random() * this.length)]);
        } else {
            bool = true;
        }
    }
    return result[0]   "     "   result[1];
}

CodePudding user response:

Getting the amount of unique items in the array looks something like

function getUniqueCount(list){
  let storage={}, count=0;
  for(let i=0; i<list.length; i  ){
    if(!storage[list[i]]){
      storage[list[i]]=true; count  ;
    }
  }
  return count;
}

But I'm not sure if that number would help you because you're not saying what you want your function to do

CodePudding user response:

Remove "()this" because this is a syntax error.

You're trying to do a math calculation:

Math.random() * this.length

Not a syntax error:

Math.random()this.length

And also, you're for loop is not doing anything, because i counts up to x only if i is lower than x. But i and x are both 0, so it will not do anything. If you're trying to make the for loop go up 1 time, just use "2", for 2 results instead of "0".

Next, result.pop() is just returning the value of "result" popped.

Remove that.

CodePudding user response:

I'm not sure what the x variable is supposed to be. If you just want to return 2 random elements from the array, there's no need for that variable or the result array. Just use two variables.

Array.prototype.random = function() {
  let item1 = this[Math.floor(Math.random() * this.length)];
  while (true) {
    let item2 = this[Math.floor(Math.random() * this.length)];
    if (item2 != item1) {
      return item1   "     "   item2;
    }
  }
}

console.log([1, 2, 3, 4, 5, 6, 7, 8].random());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related