Using JavaScript to insert specific values into an array of floats

let floats = [6, 10, 10, 10, 20, 48, 50.5, 60, 60, 78, 90];
        let evens = [{}];
        for(let i = 0; i < floats.length; i++){
            
            if(floats[i] == floats[i - 1]) { evens[evens.length - 1][i - 1] = floats[i - 1], evens[evens.length - 1][i] = floats[i]; }
            else { evens.push({}); }
            
        }
      
        evens = evens.filter(value => JSON.stringify(value) !== '{}');
      
        evens.forEach(d_ =>{
            
            let indices = Object.keys(d_);
            let offset = 1;
            let predecessor = Number(indices[0]) - 1;
            let successor = Number(indices[indices.length - 1]) + 1;
            
            if(predecessor < 0) { predecessor = 0; offset = 2; }
            if(successor > floats.length - 1) { successor = floats.length - 1; offset = 0; }
            let steps = (floats[successor] - floats[predecessor]) / (indices.length + offset);
            indices.forEach((d2_, i_) => {  floats[d2_] = floats[predecessor] + steps * (i_ + 1); })
            
        })
      
        console.log(floats);

If I have an array of floating point numbers like this:

var floats = [6.0, 10.1, 10.1, 10.1, 20.0, 32.0, 41.0, 50.5, 60.0, 60.0, 78.0];

What is the best way to adjust it so that a sequence of even numbers, say [10.1, 60.0], interpolated between their predecessors and successors?

[6.0, 9.5, 13.0, 16.5, 20.0, 32.0, 41.0, 50.5, 59.6666, 68.8333, 78.0]

10.1, 10.1, 10.1 > 9.5, 13.0, 16.5
60.0, 60.0 > 59.6666, 68.8333

Answer №1

By encapsulating a value and an offset in a closure, you can create an interpolation method that generates values between non-repeating elements.

let floats = [6, 10, 10, 10, 20, 48, 50.5, 60, 60, 78, 90],
    result = floats.map(((value, offset) => (v, i, a) => {
        if (a[i - 1] !== v && v !== a[i + 1]) {
            value = undefined;
            return v;
        }
        if (value === undefined) {
            let n = 1;
            value = a[i - 1];
            while (v === a[i + ++n]);
            offset = (a[i + n] - value) / (n + 1);
        }
        return value += offset;
    })());

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

The interlocking web of Angular dependencies

Can I begin my angular module without specific dependencies? This is my angular.module. angular.module("app", [ 'ngSanitize', 'ngAnimate', 'ui.router', 'ngMaterial', 'ngRoute', 'ngCookies', &a ...

The resizing issue of Textarea during transitions

Whenever I add the transition property to a textarea, it automatically affects the resizing function of the textarea. Is it possible to disable the transition only when resizing the textarea, but not for the textarea itself? <textarea name="" id="" cla ...

Using jQuery to extract all image sources from a parent element and remove a portion of the source URLs

I need to extract all the img src attributes from a parent element using a pointer in order to remove part of them. When I have an image selected, the src ends with _selected.jpg. Then, when I click on a link containing another image, I want to remove the ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Which specific events must I manage within the express response (stream) object to ensure proper handling when the response is completed?

I'm looking to automate the logging process for when a request completes. Here's an example of what I have so far: function (req, res, next) { var startTime = clock.now(); res.on('end'. function() { logger.trace("E ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

various locations within a hexagonal zone or figure

In my project, I am working with a simple hexagonal grid. My goal is to select a group of hexagons and fill them with random points. Here is the step-by-step process of generating these points: I start by selecting hexagons using a list of hex coordinat ...

There was an error in reading the 'rotateOnAxis' property due to its undefined nature

When working with files downloaded from three.js such as cube.obj and cube.mtl, rotating them appears to work without any issues. However, when attempting to rotate files created in Adobe Dimension like capsule.obj and capsule.mtl, an error pops up as seen ...

Record every function within the array prototype

Exploring methods that can be accessed on an array object: > console.log(Array.prototype) [] undefined > console.log(Array.prototype.push) [Function: push] Is there a way to view or log all properties/methods accessible on an object's prototyp ...

WARNING: Alert raised due to the discovery of two offspring sharing identical keys, `${item}-${index}`

I have been facing the issue of receiving an error message 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and I am not sure what is causing it. Can someone please guide me on how to resolve this problem? Any help w ...

Customizing Object Names and Parameters in Python Using the User Interface

Currently, I am in the process of developing a straightforward web application for a course project that functions as a basic travel tracker. Users have the ability to input details such as the departure date, destination, airline, and return date for mult ...

Generate a PHP array by iterating through an array of HTML input values using a for loop

I've been attempting to generate an array that includes the values of inputs within loops. As a newcomer to PHP, I have searched through various other questions without success. The process involves selecting a random number "$QuestionNoSelect" and re ...

"Learn the steps to include a success message in an HTTP POST response once a button has been

Currently, I am utilizing nodemailer along with express... I aim to incorporate a text message and loading indicator on the front-end to indicate whether the form submission is in progress or not. .ts deliverEmail(value) { console.log('em ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...

Innovative Features in Google Chrome

There is a nifty effect on Google Chrome that makes tabs light up when new content appears on the page and you are not currently viewing that tab. It can often be seen on sites like grooveshark. If anyone knows how to recreate this effect, I would greatl ...

Is there a shorter method to continuously run a function based on keypress in a specific scenario?

What is the goal of my task? My objective is to keep the movement of the TrumpHead going until another key is pressed to change its direction, similar to the game snake. I am considering creating multiple cases with functions containing cases within each ...

Nashorn: Comparing BigDecimal and number with strict equality

When working with Oracle's JDK 1.8.0_121 and using Nashorn (the JavaScript engine integrated into the JDK), the comparison new BigDecimal(1.0) === 1 returns false, while new BigDecimal(1.0) == 1 returns true: By utilizing JDK 1.8.0_121's jjs (Na ...

Ensuring Form Accuracy - Mandatory Selection from Group

Currently, in the project I am working on, there are three textboxes that need to be validated to ensure at least one of them has been filled out. I have been researching custom validation with Angular directives and found that it is possible to set the v ...

Assigning a CSS class during the $routeChangeStart event does not activate the animation, unless it is placed within a setTimeout function

Just dipping my toes into Angular, so feel free to correct me if I'm way off base here. I've been working on animating the clamps on both sides of my website to slide in upon the initial page load. You can check out the live version at: Current ...

Employing rollapply on arrays with multiple dimensions (R)

This is not a replication of the issue discussed in rollapply for two-dimensional arrays (R). Instead, it serves as an expansion on that topic - my goal is to tackle a slightly more complex task than what was outlined in that particular question. I had hop ...