Let's suppose the following object:
javascriptlet ceos = { 'bill': 1955, 'elon': 1971, 'jeff': 1964, 'erik': 1990 }
If you want to get n
random keys of the object:
javascript// Defining the number of random keys let n = 2; // Shuffling the object let shuffle = Object.keys(ceos).map((e, i, a) => { // Getting a random value between [i, a.length] // Math.floor can be translated as ~~ let j = Math.floor(Math.random() * (a.length - i) + i); // Switching the elements of positions i & j [a[i], a[j]] = [a[j], a[i]]; // Returning current value return a[i]; }); // Getting random keys let randomKeys = shuffle.slice(0, n); console.log(randomKeys); // ['elon', 'jeff']
In one line of code:
javascriptlet randomKeys = Object.keys(ceos).map((e, i, a, j = ~~(Math.random() * (a.length - i) + i)) => ([a[i], a[j]] = [a[j], a[i]], a[i])).slice(0, 2); console.log(randomKeys); // ['erik', 'elon']
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.