Fill missing numeric values in a JavaScript array


We are given an array of n entries, of which only 2 are Numbers, all other entries are null. Something like this −

const arr = [null, null, -1, null, null, null, -3, null, null, null];

We are supposed to write a function that takes in this array and complete the arithmetic series of which these two numbers are a part. To understand this problem more clearly, we can think of these null values as blank space where we need to fill numbers so that the whole array forms an arithmetic progression.

About Arithmetic Progression

A series / array of numbers is said to form an arithmetic progression if any arbitrary number n from the array is formed by adding a constant d to the (n-1) th number.

Example −

1, 2, 3, 4, 5, 6, 7, 8

Here, every succeeding number is obtained by adding a constant (1 in this case) to the preceding number.

Other examples −

1, 1, 1, 1, 1, 1, 1, 1, 1
10, 8, 6, 4, 2, 0, -2

The first element of such series is conventionally denoted by a and the constant progression in every number, the common difference, is denoted by d.

Therefore, if we denote the nth element of any such series by Tn then,

Tn = a + (n -1)d

Where, n is the 1 based index of that number.

With these things clear, let’s write code for the problem we just described. We will first try to find the first element (a) and the common difference (d) for the array. Once we have those, we will run a loop over the original array to generate the series.

Example

const arr = [null, null, -1, null, null, null, -3, null, null, null];
const arr2 = [null, null, -1, null, null, null, 12, null, null, null,
null, null, null];
const constructSeries = (arr) => {
   const map = {
      first: undefined,
      last: undefined
   };
   arr.forEach((el, ind) => {
      if(el !== null){
         if(map['first']){
            map['last'] = [el, ind];
         }else{
            map['first'] = [el, ind];
         }
      };
   });
   const { first, last } = map;
   const commonDifference = (last[0] - first[0])/(last[1] - first[1]);
   const firstElement = (first[0]) - ((first[1])*commonDifference);
   return arr.map((item, index) => {
      return firstElement + (index * commonDifference);
   });
};
console.log(constructSeries(arr));
console.log(constructSeries(arr2));

Output

The output in the console will be −

[
   0, -0.5, -1, -1.5,
   -2, -2.5, -3, -3.5,
   -4, -4.5
]
[
   -7.5, -4.25, -1,
   2.25, 5.5, 8.75,
   12, 15.25, 18.5,
   21.75, 25, 28.25,
   31.5
]

Updated on: 21-Aug-2020

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements