How can I get objects in my array to only show up once? JavaScript

Solution 1:

You could solve this by creating an array of unique random indicies, then return an array of objects that correspond to those random indices.

A set can be used to ensure all generated indices are unique.

function getNRandomObjects(objectArray,numberOfObjects) {

  // use a set to ensure at most only one instance of an index is
  // generated
  const indices = new Set();

  while(indices.size < numberOfObjects) {
    //generate a random index and add it to the set
    indices.add( Math.floor(Math.random() * objectArray.length));
  }

  // convert the set of indices into an array, 
  // then map each index to the object that corresponds
  // to that index.
  return Array.from(indices).map(i=>objectArray[i]);
}