计算数据点阵列与平均值的最大距离,并返回相关数据点

Calculate the max distance from the mean for array of datapoints and return relevant datapoint

本文关键字:数据 返回 距离 阵列 平均值 计算      更新时间:2023-09-26

假设我有一个数据数组,如下所示:

var data = [{name: "craig", value: 10}, {name: "oliver", value: 15}]

我想使用一个允许以下参数的函数:

function separateTheWheatFromTheChaff(windowSize, pointsTaken, data, valueAccessor) {}

其中windowSize是要计算的数组位置数,pointsTaken是要返回的dataPoints数。

所以我知道我需要求和来求平均值。我需要计算每个数组位置相对于平均值的math.abs,并比较每个结果以找到离平均值最远的数据点数组位置,然后将原始数据点值返回到新数组。

到目前为止,我有:

var data = [{name: "craig", value: 10}, {name: "oliver", value: -10}]
function separateTheWheatFromTheChaff(windowSize, pointsTaken, data, valueAccessor) {    
    var i;
    sum = 0;
    for(i = 0; i < windowSize; i++) {
        sum += valueAccessor(data[i]);
    }
    mean = sum/windowSize   
    for (i = 0; i < windowSize; i++) {
        Math.abs(valueAccessor(data[i]) - mean)
    }
} 
separateTheWheatFromTheChaff(5, 1, data, function(item) { return item.value });

所以我的问题是,我需要如何修改将WheatFromTheChaff函数分离以计算数组位置其中数据点离平均值最远,并返回所述数据点到新阵列。

提前谢谢,我希望这是合理的。

这里有一种方法:

编辑答案:

//create an array to store all distances
var distances = []; 
for (i = 0; i < windowSize; i++) {
    //calculate distance from mean
    var distance = Math.abs(valueAccessor(data[i]) - mean);
    //store initial datapoint with its distance from mean in array
    var datapoint_w_distance = {datapoint: data[i], 
                                dist: distance}
    distances.push(datapoint_w_distance)
}
//sort array so datapoint with largest distance from mean is first
distances.sort(function(a,b) {return b.dist-a.dist});
//use the pointsTaken parameter to get the correct number of original datapoints back
var wheat = [];
for (var j=0; j < pointsTaken; j++) {
   wheat.push(distances[j].datapoint)
}
return wheat;

例如,如果

var data = [{name: "a", value: 20}, 
            {name: "b", value: 10},
            {name: "c", value: 90},
            {name: "d", value: 100},
            {name: "e", value: 0}]

则CCD_ 1返回阵列CCD_

工作小提琴:https://jsfiddle.net/ubbrx3u3/5/