Pavan Kumar
Pavan Kumar

Reputation: 33

Fill the array with average of result with left and right values in an array

I have an array like this

var salaries=[30000,undefined,40000,50000,undefined,70000] 

here i want fill the undefined values with average of left and right values. like this.

modified_salaries=[30000,35000,40000,50000,60000,700000]

Actually i tried a lot of times and getting confusion to achieve this.

please help me, is there any solution for this type of calculation.

Edit: if the array is

var salaries=[30000,undefined,undefined,40000,50000,undefined,70000]

the result should be:

modified_salaries=[30000,33000,36000,40000,50000,60000,70000]

Upvotes: 0

Views: 121

Answers (4)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15290

Can be do in this way.

var salaries = [30000, undefined, 40000, 50000, undefined, 70000];

var finalSal = [];

salaries.forEach(function(val, key) {

    if (val) {
        finalSal.push(val);
    } else {
        finalSal.push((salaries[key - 1] + salaries[key + 1]) / 2);
    }
});

Upvotes: 0

answer99
answer99

Reputation: 251

Try like this:

<div></div>

var salaries=[30000,undefined,40000,50000,undefined,70000];
var modified_salaries = [];

for(var i=0; i<salaries.length; i++) {
    if(salaries[i] === undefined) {
         modified_salaries.push((salaries[i-1] + salaries[i + 1])/2);
    } else {
        modified_salaries.push(salaries[i])     
    }
}

$("div").text(modified_salaries)

Jsfiddle

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

var salaries = [30000, undefined, 40000, 50000, undefined, 70000]
var modified_salaries = salaries.map(function(x, i) {
    return typeof x === "undefined" ? (salaries[i - 1] || 0 + salaries[i + 1] || 0) / 2 : x;
});

console.log(modified_salaries);

Upvotes: 2

Tushar
Tushar

Reputation: 87223

See the comments inline in the code:

var salaries = [30000, undefined, 40000, 50000, undefined, 70000];

var modified_salaries = []; // Define empty array

for (var i = 0; i < salaries.length; i++) {
    if (salaries[i]) {
        modified_salaries.push(salaries[i]); // If not undefined, push it as it is
    } else {
        // Check if prev and next element exists, use 0 otherwise to calculate average.
        average = ((salaries[i - 1] || 0) + (salaries[i + 1] || 0)) / 2;

        modified_salaries.push(average); // Push average in new array.
    }
}
console.log(modified_salaries); // Log new array

Demo

Upvotes: 3

Related Questions