我正在学习 JavaScript 并尝试将其应用于统计采样。 下面的函数不起作用,但假设:
- 数组=要研究的人群
- 样本 = 从总体中抽取的样本
- 元素=总体中的每个观察
const generateSample = array => {
var sample = []
array.filter(element => {
(element in sample) ? return null : sample = [...sample, element]
})
}
最佳答案
经过一些研究,这是我从数组中检索大小为 N 的样本时发现的
- 打乱数组
- 对打乱后的数组进行切片以获得大小为 N 的样本
注意: shuffleArray
函数是在 question 的帮助下创建的。
和 answer
下面是解决问题的两个函数
// Function that shuffles an array
const shuffleArray = array => {
if (array.length === 1) return array
const randomIndex = Math.floor(Math.random() * array.length);
const randomElement = array[randomIndex]
array = array.filter((_, i) => i !== randomIndex)
return [randomElement, ...shuffleArray(array)];
};
// Function that returns sub array from array
const subArray = (array, n) => array.slice(0, n)
const population = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const shuffled = shuffleArray(population)
console.log( shuffled )
console.log(subArray(shuffled, 4))
关于javascript - 我可以使用 array.filter() 从数组中获取样本元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032421/