如何通过打字稿中的方差过滤一组数据?

时间:2017-12-19 12:49:50

标签: javascript typescript

假设我有一组这样的数据,过去4小时内每分钟有一行:

[
{ X:1000, Y:2000, Z:3000, DateTime: 12/15/2018 12:00  },
{ X:998, Y:2011, Z:3020, DateTime: 12/15/2018 12:01  }
]

我需要一组属性名称,其值在所有行的20%变化范围内。因此,如果上面的Y和Z符合此条件但X不符合,则输出应如下所示:

[Y, Z]

我可以使用哪些打字稿代码来执行此操作?

1 个答案:

答案 0 :(得分:0)

我不确切地知道你的问题中“方差”或“方差百分比”是什么意思。我刚用这个公式来计算方差:https://www.wikihow.com/Calculate-Variance 对于方差百分比,我简单地将方差除以平均值并以百分比表示。 您可以使用更正确的实现替换我的calculateVariancePercentage

const ACCEPTABLE_VARIANCE_THRESHOLD = 20;

const dataset = [
    { X:1000, Y:2000, Z:3000, DateTime: '12/15/2018 12:00'  },
    { X:998, Y:2011, Z:3020, DateTime: '12/15/2018 12:01'  }
];


const calculateVariancePercentage = (data) => {
    const meanValue = data.reduce((sum, element) => sum + element, 0) / data.length;
    const sumOfDeviations = data.reduce((sod, element) => Math.pow(element - meanValue, 2), 0);
    const variance = sumOfDeviations / (data.length - 1);
    return variance / meanValue * 100;
}

const variables = Object.keys(dataset[0]).filter(key => key !== 'DateTime');

const result = variables.filter(variable => {
    const varData = dataset.map(row => row[variable]);
    const varianceInPercentage = calculateVariancePercentage(varData);
    console.log(varianceInPercentage);
    return calculateVariancePercentage(varData) <= ACCEPTABLE_VARIANCE_THRESHOLD;
});

console.log(result);