1

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.

2
  • So, sort the array once you're done? Commented Jun 9, 2020 at 12:25
  • 1
    please add a possible result with comments. Commented Jun 9, 2020 at 13:03

2 Answers 2

1

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);
}, []);

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

1 Comment

thx for that approach. but i need to have the newly generated random numbers added until the SUM is bigger than the "gap". now its adding a random number for every 'int' of the gap.
0

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; }

1 Comment

@Tobi changed with no gap greater than 4

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.