Как создать массив строк из случайной длины и случайных значений
Есть функция, которая выводит рандомную длину заданного массива. Как сделать так, чтобы выводился массив случайной длинны из случайных значений? Значения, которые рандомно выводятся не должны повторяться.
function getRandomNumber(min, max) {
const minNumber = Math.ceil(min);
const maxNumber = Math.floor(max);
if ( maxNumber < minNumber){
throw new RangeError('Значение максильного числа не должно быть меньше значения минимального числа');
} else if (maxNumber === minNumber) {
throw new RangeError('Максимальное значение числа не должно быть равно минимальному значению числа. Результат + min');
} else {
return Math.floor(Math.random() * (maxNumber - minNumber + 1)) + minNumber;
}
}
const features = ['wifi', 'dishwasher', 'parking', 'washer', 'elevator', 'conditioner'];
function getArray(features) {
const maxLength = features.length;
const lengthOfArray = getRandomNumber(1, maxLength);
const array = [];
for(var i = 0;i < lengthOfArray;i++) {
const indexOfEl = getRandomNumber(0, 5);
const el = features[indexOfEl];
if (!array.includes(el)) {
array.push(el);
}
}
return array;
}
Ответы (3 шт):
Автор решения: Igor
→ Ссылка
const features = ['wifi', 'dishwasher', 'parking', 'washer', 'elevator', 'conditioner'];
function getArray(features) {
const maxLength = features.length;
const lengthOfArray = getRandomNumber(1, maxLength);
const array = [];
while (array.length < lengthOfArray) {
const indexOfEl = getRandomNumber(0, maxLength - 1);
const el = features[indexOfEl];
if (!array.includes(el)) {
array.push(el);
}
}
return array;
function getRandomNumber(from, to) {
return Math.floor(Math.random() * (to - from + 1)) + from;
}
}
console.log(JSON.stringify(getArray(features)));
Автор решения: Vasyl
→ Ссылка
const createRandomUniqArray = (array) =>{
const arr = Array.from(array);
const arrayNew = new Array(getRndInteger(1, arr.length));
for (let id=0; id<arrayNew.length; id++ ){
arrayNew[id]=arr.splice(getRndInteger(0, arr.length-1), 1).join();
}
return arrayNew;
};
function getRndInteger(min, max) {
if (min<0||max<=min){
throw new Error('Диапазон неверен');
}
return Math.floor(Math.random() * (max - min) ) + min;
}
Автор решения: Valeriya
→ Ссылка
const features = ['wifi', 'dishwasher', 'parking', 'washer', 'elevator', 'conditioner'];
const getRandomPositiveInteger = (a, b) => {
const lower = Math.ceil(Math.min(Math.abs(a), Math.abs(b)));
const upper = Math.floor(Math.max(Math.abs(a), Math.abs(b)));
const result = Math.random() * (upper - lower + 1) + lower;
return Math.floor(result);
};
const getNewArray = () => {
const newArray = [];
const newArrayLength = getRandomPositiveInteger(1, features.length);
for (let i = 1; i <= newArrayLength; i++) {
const options = features.shift();
newArray.push(options);
}
return newArray;
}
getNewArray();