Skip to content
Advertisement

how to calculate zero values in array between two valid numbers?

I have an array of numbers with some 0 values. I want to fill 0 with the linear difference between two valid values.

let arr = [10,0,0,16,17,0,23] I am using the below code to calculate the linear difference between the two data points if they have zero between them like 10 and 16 have two indexes with 0, if need any further info regarding this data feel free to comment below any answers are accepted that can help.

let arr = [10,0,0,16,17,0,23]
//required result [10,12,14,16,17,20,23]
// here is my code

const getValueIf = (item, index, array) => {
  const lastindex = array.length - 1;
  const zeroWithFirst = index !== 0 && item === 0;
  const zeroWithLast = index !== lastindex && item === 0;
  const firstZero = index === 0 && item === 0;
  if (firstZero) {
    return array[index] = ifZeroToNumber(array, index) ;
  }
  if (zeroWithFirst || zeroWithLast) {
    if (zeroWithFirst && !zeroWithLast) {
      return array[index - 1];
    }
    if (!zeroWithFirst && zeroWithLast) {
      return array[index + 1] === 0 ? array[index + 2] : array[index + 1];
    }
    array[index] =
      (ifZeroToNumber(array, index) - array[index - 1]) / 2 +
      array[index - 1];
    return (
      (ifZeroToNumber(array, index) - array[index - 1]) / 2 + array[index - 1]
    );
  } else {
    return item;
  }
};

const ifZeroToNumber = (array, index) => {
  let num = 0;
  for (let i = 1; i <= array.length; i++) {
    if (num === 0 && array[index + i]) {
      num = array[index + i];
    }
  }
  if (!num) {
    num = array[index - 1];
  }
  return num;
};
let removeZero = arr.map((value, index) =>
    getValueIf(value, index, arr)
  );
console.log(removeZero)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Advertisement

Answer

Let’s loop through the array, once we find a zero, if it is the first one, remember the position, if it is the last, compute the step and fill:

function fill(a) {

    let start = -1
    let zero = false

    for (let i = 0; i < a.length; i++) {
        if (a[i] === 0) {
            zero = true
            continue
        }

        if (zero && start >= 0) {
            let step = (a[i] - a[start]) / (i - start)
            for (let j = start + 1; j < i; j++)
                a[j] = a[j - 1] + step
        }

        zero = false
        start = i
    }

    return a
}

console.log(...fill([0, 0, 1, 0, 0, 4, 0, 0, 7, 8, 9, 0, 11, 0, 0]))
console.log(...fill([12, 23, 0, 0, 0, 25, 0, 0, 10]))
console.log(...fill([10, 0, 0, 16, 17, 0, 23]))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement