* Returns random element from the given array. * * @template T The type of the elements to pick from. * * @param array The array to pick the value from. * * @throws {FakerError} If the given array is empty. * * @example * faker.helpers.arrayElement(['cat', 'dog', 'mouse'])
(array: ReadonlyArray<T>)
| 938 | * @since 6.3.0 |
| 939 | */ |
| 940 | arrayElement<const T>(array: ReadonlyArray<T>): T { |
| 941 | if (array.length === 0) { |
| 942 | throw new FakerError('Cannot get value from empty dataset.'); |
| 943 | } |
| 944 | |
| 945 | const index = |
| 946 | array.length > 1 ? this.faker.number.int({ max: array.length - 1 }) : 0; |
| 947 | |
| 948 | return array[index]; |
| 949 | } |
| 950 | |
| 951 | /** |
| 952 | * Returns a weighted random element from the given array. Each element of the array should be an object with two keys `weight` and `value`. |