JavaScript: Update missing values in an array by assigning the average of its neighboring values

Consider the following array:

[5,2,null,5,9,4]

To replace the null value with the average of the previous and next values (2 and 5), you can do the following:

[5,2,3.5,5,9,4]

If there are consecutive null values in an array:

[5,2,null,null,9,4]

You can replace them with step values between 2 and 9, like this:

[5,2,4.33,6.63,9,4]

Just to clarify, I'm not using this for a homework assignment but rather experimenting with the functionality offered by the Chartist-js library.

Below is a snippet that demonstrates how to replace null values with the average of neighboring elements:

var seriesData = [5,2,null,5,null,4]

seriesData.forEach(function(value, index){
    if ( value === null ) {
        var prev = seriesData[index - 1];
        var next = seriesData[index + 1];
        seriesData[index] = (prev + next) / 2;
    }
});

=> [5, 2, 3.5, 5, 4.5, 4]

Answer №1

It appears that a Chart issue is causing the problem. Here is a basic solution to address it, with room for optimization:

function test(){
  var arr = [5,3,2,null,null,9,4, null, null, null, 10, null, 12],
    ind = -1,
    prevIndex,
    nJumps, valJump;

for( var currIndex = 0; currIndex< arr.length; currIndex++ ){
  if( arr[ currIndex] == null ){
    continue;
  }else if( prevIndex === undefined || (nJumps = (currIndex- prevIndex)) === 1 ){
    prevIndex = currIndex;
    continue;
  }

  valJump = (( arr[ currIndex ] - arr[ prevIndex ]) / nJumps);

  ind = (+prevIndex);
  while( ++ind < (+currIndex) )
      arr[ ind ] = (arr[ ind-1 ]) + valJump;

  prevIndex = currIndex;
}

return arr;
}

Answer №2

Your initial issue has been successfully resolved:

let numbers = [7, 4, undefined, 7, 12, 9];

let finalResult = numbers
  .map(function (num) {
    if (num === undefined) {
      return (numbers[numbers.indexOf(num) - 1] + numbers[numbers.indexOf(num) + 1]) / 2 ;
    }

    return num;
  });

console.log(finalResult); // [7, 4, 5.5, 7, 12, 9]

Regarding the second problem, I'm unsure about the specifics of your "two steps" requirement.

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

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

Troubles encountered with switching npm registry

In my Vue 2.7 project with vuetify, I initially installed dependencies using a custom local npm registry, acting as a proxy to the default npm. As the project has expanded, I've started using git actions to deploy to a development server, with varying ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...

What is the best way to programmatically insert new rows into a table

I am currently working with the foundation 5 framework (not sure if this is relevant). I need to ensure that each CELL is treated as a distinct item/value when passing information to another page, and I am unsure of how to approach this issue. It should cr ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

Creating a Modal Popup with Bootstrap 5 in Asp.net using C#

Despite trying everything, I was unable to achieve success. <script type="text/javascript"> function openModal() { var myModal = new bootstrap.Modal(document.getElementById('KullaniciAramaSonuc'), {}); myModal.show(); ...

In the realm of JavaScript, consider logging a message to the console if the array value happens to be

I'm facing an issue with the code below. My goal is to log 'empty array value' whenever there is an empty value, but it's not functioning as expected. Can anyone advise me on what the value of an empty array item is and how I can modify ...

Starting a new array with values from a pre-existing array in R

So I have this array: a<-c(6,77,98,88,3,10,7,5) What I'm trying to do is create another array that includes the first, sixth, and eighth elements. This new array, let's call it b, should look like this: b = (6,10,5) Is there a simple way t ...

Scrolling through a lengthy table without affecting the overall window scroll

I currently have a situation where I have a table positioned below several div elements: <div></div>...<div></div> <div id="tablecontent"> <table>...</table> </div> My goal is to make the table scrollable ...

Monitor and retrieve live updates of links using Javascript

I am a beginner in JavaScript and recently developed a successful Chrome extension for Dubtrack. I have been struggling to find a way to make my injected script run in real-time and grab the latest YouTube music video URL. Any assistance would be greatly a ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

React and Array JavaScript combined to create a dynamic To DoList application

First and foremost, I would like to apologize for any grammatical errors in my English, as I am Brazilian. Currently, I am working on creating a React test application that renders a to-do task list using the JavaScript map method. However, I am facing an ...

Step-by-step guide on transferring form data from an Ionic application to parse.com MBaaS through the REST API

Today is my first day with Ionic/Angular, and I'm diving in out of necessity. I've been using tutorials and documentation to create a demo/test app that submits data to the Parse.com MBaaS service. However, I seem to be stuck somewhere and clue ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

Error: The 'export' key was not expected. (JavaScript code: 33)

The browser error message lacks detail, and my attempts to find a solution have been unsuccessful. An error only occurs when I include this line at the top of my ToDo component: import Checkbox from '@material-ui/core/Checkbox'; It is important ...

Running a node.js project on the client side without using npm for deployment

Looking for a solution to efficiently deploy my nodejs project with frequent updates. The site does not have npm available, so I have to package the node_modules every time, which results in a large file size (80MB) that takes a long time to send via ftp t ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

Showing only the objects that are marked as true in the component (React)

I have implemented two key React components. One of them is VideoGameList.js, it serves as an export of an array containing multiple objects. const VideoGameList = [ { id: 1, title: "Fire Emblem Engage", src: vg01, releaseDate: ...