0

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

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

You've assumed that if the array begins or ends with null, the interpolation will be between the first/last value and zero. I would assume no interpolation should be done, but the brief is unclear.
Thanks, that looks great! I wasn't that far :) I will detail how the interpolation should work for beg and end values in the question, but the assumption is that it should take the same value as the next valid element, or previous (if end value). One question, I don't understand how I set up the gap length. If the gap is let's say 3 values or more I would like to keep the null values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.