0

I have an array such as:

array=['a','b','c','d','e','f'];

I want to delete a random 2 elements. How can I do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
sally
  • 1
  • 3

1 Answers1

0

To get two unique items from the array, and if you don't mind mutating the original array, you can use splice() to remove the selected item from the array so it won't be picked when you run it a second time:

var firstRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
var secondRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);

If you use a utility library such as lodash, you may already have a function available to do this for you. For example, lodash provides sample(). So if you were using lodash, you could just do something like this to get an array of two random items:

var results = _.sample(array, 2);
Trott
  • 66,479
  • 23
  • 173
  • 212
  • I tried "var results = _.sample(array, 2);" But I can not random 2 objects.It select only one object – sally Apr 22 '15 at 21:50