Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pick random objects from an array with a specific property wich is unique

I’m looking for a method to pick random objects from an array of objects where a specific property has a unique value.

Example:

const array = [
  {
    name:'foo',
    message: 'hello'
  },
  {
    name:'foo',
    message: 'world'
  },
  {
    name:'bar',
    message: 'hello'
  },
  {
    name:'bar',
    message: 'world'
  },
]

function theMagicMethod(elementsCount, specificUniqueProperty){
// ...
};

console.log(theMagicMethod(2, name));

// Expected output: [{name:'foo', message:'hello'},{name:'bar', message:'hello'}]
// or [{name:'foo', message:'hello'},{name:'bar', message:'world'}]
// etc...

// BUT NEVER WANT: [{name:'foo', message:'hello'},{name:'foo', message:'world'}]

I’ve tried to use do … while or while … but it always crash when I conditionnally add an element to my result array.:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


let items = [];
do{
  let item = array[Math.floor(Math.random()*array.length)];

  let found = false;
  for(var i = 0; i < vendors.length; i++) {
      if (vendors[i].Name == 'Magenic') {
          found = true;
          break;
      }
  }

  if(!found){
    items.push(item)
  }

} while (items.length < 3)

>Solution :

Shuffle the objects, use a set to filter unique values, return the first N…

// fy shuffle, thanks to https://stackoverflow.com/a/2450976/294949
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
  return array;
}

function theMagicMethod(elementsCount, specificUniqueProperty) {
  let shuffled = shuffle(array.slice());
  let uniqueValues = new Set()
  let unique = shuffled.filter(el => {
    const value = el[specificUniqueProperty];
    const keep = !uniqueValues.has(value)
    uniqueValues.add(value);
    return keep;
  })
  return unique.slice(0, elementsCount);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading