Find the furthest distance from the average in a set of data points and identify the corresponding data point

Imagine having an array of data structured like this:

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

My goal is to create a function that can accept parameters like:

function findExtremeValue(windowSize, pointsToTake, data, valueAccessor) {}

Where windowSize represents the number of positions in the array to consider, and pointsToTake is the desired number of data points to be returned.

To achieve this, I need to calculate the mean by obtaining the sum of all values. Then, for each array position, I must find the absolute distance from the mean and identify which data point is farthest from the mean. This data point should then be added to a new array.

Here is the initial code I have:

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

function findExtremeValue(windowSize, pointsToTake, data, valueAccessor) {
    var i;
    var sum = 0;
    for(i = 0; i < windowSize; i++) {
        sum += valueAccessor(data[i]);
    }
    var mean = sum/windowSize;   
    for (i = 0; i < windowSize; i++) {
        Math.abs(valueAccessor(data[i]) - mean);
    }
} 

findExtremeValue(5, 1, data, function(item) { return item.value });

My question is, how should I modify the findExtremeValue function in order to identify the array position with the data point that is farthest from the mean, and then add that data point to a new array?

Thank you in advance for your help, and I hope this explanation is clear.

Answer №1

To achieve this, follow these steps:

MODIFIED SOLUTION:

// initializing an array to store distances
var distances = []; 
for (i = 0; i < windowSize; i++) {
    // calculating distance from the mean
    var distance = Math.abs(valueAccessor(data[i]) - mean);
    // storing initial data point with its distance from mean in the array
    var datapoint_w_distance = {datapoint: data[i], 
                                dist: distance}
    distances.push(datapoint_w_distance)
}
// sorting the array so the data point with the largest distance from the mean is first
distances.sort(function(a,b) {return b.dist-a.dist});
// using the pointsTaken parameter to retrieve the correct number of original data points
var wheat = [];
for (var j=0; j < pointsTaken; j++) {
   wheat.push(distances[j].datapoint)
}
return wheat;

For instance, if

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

then

separateTheWheatFromTheChaff(5, 2, data, function(item) { return item.value })
will yield the array
[{name: "d", value: 100}, {name: "c", value: 90}]

Live example: https://jsfiddle.net/ubbrx3u3/5/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

Random Label Selector in Visual Basic code

Greetings! I am currently working with Visual Basic in Visual Studio Express 2013 and facing a challenge. My goal is to develop a function that can extract a list of first names from a text file and store each name in an index within an array. However, ins ...

Integrating a fictitious style using jQuery

Having some trouble with this code snippet. The issue arises when trying to apply the following style using jQuery. CSS .arrow_box { position: absolute; width: 24px; border-radius: 30px 30px 3px 3px; height: 17px; float:left; } .arrow_box:after { bord ...

How to fetch images from a database in CodeIgniter by utilizing JSON and AJAX functions?

Trying to retrieve an image using ajax/json format for the first time, all variables are displaying except the image. The name of the image is visible when inspecting the element in the browser and it is saving correctly into the image folder. I need help ...

JavaScript alerts

Can anyone recommend a quality library with beautifully animated popups? Specifically, I need a popup that allows for basic HTML fields such as text areas and more.... I am in search of a popup that will overlay on the current page, rather than opening a ...

Is it possible for me to utilize window.top within the .js file?

Within my GWT code, I am transferring a variable to a JSP file. The process looks like this: <html> <head> <script type="text/javascript"> alert("Inside the JSP file"); var criticalPath = window.top.criticalPath; ...

The lack of definition for e.PreventDefault causes an error

In my code, I have a registerAjax(e) function: function registerAjax(e) { e.preventDefault(); let userData = { username: $("#username").val(), password: $("#password").val(), }; $.ajax({ method: "POST", url: kinveyBaseUrl + "user/" + kinve ...

Angular's isteven-multi-select Component: A Versatile Selection Tool

Is it possible to utilize isteven-multi-select with ng-model? My goal is to have certain items appear as chosen when the page loads using the isteven-multi-select module. I've tried using ng-model in the HTML page to populate the isteven-multi-select ...

Creating clones of <li> elements using JQuery and appending them to the end of a <ul> list

I have a regular ul li list and I am looking to add an additional li based on the first one in the list. Here is the HTML: <div id="gallery"> <ul> <li>Point Nr 1<p>lol</p></li> <li>Point Nr 2</li> <li> ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

Issues have been encountered with activating checkboxes on Internet Explorer while utilizing ASP.NET CheckBox controls

I'm facing an issue with an HTML form that includes two disabled checkboxes and an image with an onclick event intended to display a popup and enable the checkboxes: <input id="chk1" type="checkbox" disabled="disabled" /> <input id="chk2" ty ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...

Attempting to convert a Raw image file and upload it onto the server

I am currently attempting to upload an image to my server using PHP. I have two files for this task - index.php and myscript.php. Index.php <div id="results">Your captured image will appear here...</div> <h1>Mugshot Test Page& ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

The Vue.js checkbox linked to a v-model with a value set to false is currently marked as

I'm attempting to create a to-do list resembling the Eisenhower matrix, but I'm encountering an issue with v-bind and v-model being triggered incorrectly. How can I resolve this bug? https://i.sstatic.net/iIhqR.png Code inspiration from Vue.js T ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

Netlify Lambda function with Expressjs generates a fresh session for each incoming request

Good Evening, After successfully running my Expressjs API locally without utilizing lambda functions, I encountered an issue where every request created a new session once the lambda function was introduced. Below is the implementation of server.js and Das ...

Debounce fails to honor the specified timeout period

I'm currently working on implementing a debounce function to handle an HTTP request function. The code is very similar to the example provided below, with only minor changes in function names. To start off, here's the debounce function I am usin ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

The art of parsing a file one line at a time

My goal is to read a file one line at a time. Here is the file I want to read: polkit|0.105 NetworkManager|0.9.4.0 GConf|3.2.5 libgnome-keyring|3.4.1 mozilla-nss|3.13.5 network-manager-applet|0.9.4.1 ... This is the script I am using: COUNTER=1 until [ ...