Reputation: 93
I have an array like this:
[0, 24.646213151927437, 27.737256235827665, 29.08326530612245]
I want to fill every space between the elements which are greater than 4 with random numbers. Like this:
var arr = [0, 24.646213151927437, 27.737256235827665, 29.08326530612245];
var length = arr.length;
for (var j = 0; j < length;) {
var spacebetween = arr[j + 1] - arr[j];
if (spacebetween > 4) {
// fill the space until the sum of numbers is greater than space between
var m = Math.random() * (3 - 1 + 1);
for (k = m; k < spacebetween;) {
arr.splice(j, 0, parseFloat(k));
m = Math.random() * (3 - 1 + 1);
k = k + m;
}
}
j++;
}
console.log(arr);
The problem is with splice()
, the index is shifting and I have no idea how to solve this. The new numbers should stay in ascending order within the array.
Upvotes: 1
Views: 691
Reputation: 22320
Is there a way to add elements with .splice() during a loop in javascript?
Yes, the solution is to simply start from the end and decrement, the new entries will no longer disturb the process:
changed with no gap greater than 4
let arr = [ 0, 24.646213151927437, 27.737256235827665, 29.08326530612245 ]
for (let j=arr.length; --j;) // inside loop j start to (arr.length-1) to value==1 ( value zéro mean false)
{
let vRef = arr[j-1]
, vMin = arr[j] -4
;
while (vMin > vRef)
{
vMin = (Math.random()*4) + vMin
arr.splice( j, 0, vMin )
vMin -= 4
}
}
console.log( JSON.stringify( arr,0,2 ))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 1158
Instead of looping through the array (with a changing length), you can use a reduce to loop through the original array and push updates to the accumulator
var arr = [0, 24, 27, 29];
var newArr = arr.reduce((accumulator, cur, i) => {
var needTempArr = arr[i + 1] && (arr[i + 1] - cur);
// if need temp array, generate it; otherwise, empty array
var tempArr = needTempArr
? Array(needTempArr).fill(0).map(() => Math.random())
: [];
return accumulator.concat(cur, tempArr);
}, []);
Upvotes: 1