Reputation: 33
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
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
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)
Upvotes: 0
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
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
Upvotes: 3