Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var getRandomItem = function(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}
// original array
var arr = [4, 3, 1, 6, 9, 8, 5];
// number of random elements to get from arr
var n = 4;
if (n > arr.length) {
  alert('n must be less than or equal arr length');
}
var count = 0;
// new array to push random item in
var randomItems = []
do {
  var item = getRandomItem(arr);
  randomItems.push(item);
  // update the original array and remove the recently pushed item
  arr.splice(arr.indexOf(item), 1);
  count++;
} while(count < n);
console.log(randomItems);
console.log(arr);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
tramyardgpro
0viewers