Home > Web Front-end > JS Tutorial > How to randomly extract several array elements from an array in JS

How to randomly extract several array elements from an array in JS

高洛峰
Release: 2017-01-14 13:14:47
Original
1771 people have browsed it

How to randomly remove an element or several elements from an array in JS.

If the array is

var items = ['1','2','4','5','6','7','8','9','10'];
Copy after login

1. Randomly remove an element from the array items

var item = items[Math.floor(Math.random()*items.length)];
Copy after login

2. Randomly select several elements from the previous random array

function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
var items = ['1','2','4','5','6','7','8','9','10'];
console.log( getRandomArrayElements(items, 4) );
Copy after login

The above is the JS method that the editor introduces to you to randomly extract several array elements. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more related articles on JS's method of randomly extracting several array elements from an array, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template