1

I want to draw 3 numbers from the array

let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

but after drawing each of them, the chosen number should be removed from the num array.

For e.g. 0 is chosen, the next two can be drawn from

let num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

and so on.

Does anyone know how to do that in the most efficient way?

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26
W12
  • 57
  • 7
  • This doesn't appear to be specific to [tag:angular] _or_ [tag:typescript]. Don't you just want to pick randomly from a [tag:javascript] array? – jonrsharpe Mar 15 '23 at 17:47
  • Does this answer your question? [Sampling a random subset from an array](https://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array) – jonrsharpe Mar 15 '23 at 17:47

2 Answers2

2

Array.prototype.splice() does exactly that.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

console.log("arr: " + arr);

let removed = arr.splice(0,1);

console.log("removed: " + removed);
console.log("arr: " + arr);

removed = arr.splice(4,3);

console.log("removed: " + removed);
console.log("arr: " + arr);
Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26
1

If you need to remove multiple indices from an array, you need to remove them in reverse numerical order so that the act of removing each item does not disturb the positions of elements before it in the array.

let num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

let indices = [2,0,3]

let result =
  [...indices].sort((a,b)=>b-a)
  .reduce((a,c)=>(a.unshift(...num.splice(c,1)),a),[])

console.log(result)
console.log(num)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27