Finding index of left and right element's index of null in an array in Javascript

Viewed 135

I'm trying to use simple linear interpolation to replace any nulls in my data array. I need to find left and right values in order to get the linear interpolation calculation. I've coded this following,

const data = [null, null, 537309, 514619, 548638, 618428, 615091, 695349, 828929, 925076, 741585, 650574, 730432, 795618, 997527, 1112017, 1137697, 1231562, 1210135, 1204056, 1252409, 1261298, 1230198, 1336902, 1420173, 1502653, 1553030, 1514224, 1397548, 1353077, 1336532, 1250078, 1274630, 1231772, 1295328, 1249025, null, 1394515, null, null];

let result = [];
let i=1;
let j=1;
let before;
let after;

data.forEach((elem,index)=>{
    if(elem === null || typeof elem !=="number"){
         const condition = !Object.is(null, data3[before]) && !Object.is(null, data3[after])
         do {
         i = i +1;
         j = j +1;
         after = index + j;
         before = index - i;
         result.push({before:before, index:index,after:after})
         } while (!condition);
  }
})
console.log(result)
[
  { before: -2, index: 0, after: 2 },
  { before: -2, index: 1, after: 4 },
  { before: 32, index: 36, after: 40 },
  { before: 33, index: 38, after: 43 },
  { before: 33, index: 39, after: 45 }
]

As you can see, there are some elements that would return me undefined if I put it back to data. such as data[-2], data[43] and data[45] would return undefined. But I'll be calling this whole function recursively so that each null will be replaced by utilizing previously calculated output.

Expected Output should be the two nearest indexes from null index within the range of data:

[
  { before: 2, index: 0, after: 3 },
  { before: 0, index: 1, after: 2 },
  { before: 35, index: 36, after: 37 },
  { before: 36, index: 38, after: 37 },
  { before: 37, index: 39, after: 38 }
]

Here you can test linear interpolation https://dmytropaduchak.github.io/simple-interpolation-example/#linear and examples from https://www.npmjs.com/package/simple-linear-interpolation

const points = [{ x: 1, y: 1}, { x: 2, y: 2 }];
const calculate = linearInterpolation(points);

calculate({ x: 1.5 }); // y -> 1.5
calculate({ y: 1.5 }); // x -> 1.5
0 Answers
Related