Service Now - Get Random Array Item

Thursday Jan 9, 2020

Sometimes it’s helpful to get a random item from an array. Here’s how.

Code

Here’s the code:

  function randomItem(items) {
		if (!Array.isArray(items)) {
			throw "Argument must be an array: " + items;
		}
		if (items.length == 0) {
			throw "Array argument is empty";
		}
		return items[Math.floor(Math.random() * items.length)];
	}