H
H
heisenberg12021-06-10 19:52:30
JavaScript
heisenberg1, 2021-06-10 19:52:30

What function is suitable for getting an array of strings of random length?

What function can be used to get an array of strings of random length from values ​​that should not be repeated from the photos object?

const photos = {
colors: [
'white', 
'red', 
'blue',
'green', 
'brown',
'black'
], 
link: [
'firstLink',
'secondLink',
'thirdLink'
]
};


I tried with the help of these functions, but something does not work for me to register as it should
const getRandomArrayElement = (elements) => {
  return elements[_.random(0, elements.length - 1)];
};

function getRandomElement () {
 return {
   colors: getRandomArrayElement(colors),
   link: getRandomArrayElement(link)
}
};

const commonArr = new Array(5).fill(' ').map(() => getRandomElement());
console.log(commonArr)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-06-10
@sergiks

You can go through all the elements and randomly decide for each whether to include it in the next selection:

const getSome = (arr) => arr.filter(() => Math.random() >= 0.5);

The downside here is the probability distribution. Most often, the length will be about half the length of the original. And rarely can you get an array of zero length, or a complete original.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question