Vincent Teyssier
Vincent Teyssier

Reputation: 2217

Javascript: Interpolate gaps in array of number given gap length

Given an array that can contain numbers or null values

[15, 20 ,30, null, 10, 14, null, null, 45, 70, null, null, null, 36, 19]

An interpolate function should return the array with the interpolated numbers only if the gap is less or equal than x consecutive values.

Result array would look like:

[15, 20, 30, 20 10, 14, 24.33, 34.67, 45, 70, null, null, null, 36, 19]

I'm thinking that my interpolated value should look like:

interpolated value = previous_valid_value - ( (next_valid_value - previous_valid_value) / (gap_length+1) )

I'm trying the following code, but it doesn't account for a 2 or more gap, and what about if I have negative values, or if the gap is at beginning or end of the array. I'm a bit lost how to approach this. Some help would be greatly appreciated

i = 0
array.forEach(element => {
    if (element === null) {
        j = i-1
        while (array[j] === null) {
            j = j - 1
        }
        previous_valid_element = array[j]
        j = i + 1
        while (array[j] === null) {
            j = j + 1
        }
        next_valid_element = array[j]
        element[i] = (next_valid_element - previous_valid_element) / 2
    }
    i = i + 1
})

EDIT: if beginning or end of the array is null then it should take the next or previous available value

Upvotes: 0

Views: 243

Answers (1)

Kirill Savik
Kirill Savik

Reputation: 1278

Please use this.

i = 0
array.push(0)
array.unshift(0)
array.forEach(element => {
    if (element === null) {
        j = i - 1
        while (array[j] === null) {
            j = j - 1
        }
        previous_valid_element = array[j]
        console.log(previous_valid_element)
        j = i + 1
        while (array[j] === null) {
            j = j + 1
        }
        next_valid_element = array[j]
        cond = next_valid_element > previous_valid_element ? true : false
        step = Math.abs((next_valid_element - previous_valid_element)) / (j - i + 1)
        array[i] = cond ? array[i-1] + step : array[i-1] - step
    }
    i = i + 1
})
array.pop()
array.shift()

Does this help you?

Upvotes: 2

Related Questions