Search code examples
javascriptarraysmathnumbersformula

How to make an array with values longer (JavaScript)


Array = [0, 4, 10, -20, 10, 20, 50]

I want this array after an formula that makes it look like this or similar

Array = [0, 2, 4, 7, 10, -5, -20, -5, 10, 15, 20, 35, 50] 

What it does is, it checks the distance between the numbers and then divides the distance by 2, then it adds it to the middle of those values.


Solution

  • You can iterate over the array (e.g. using forEach), pushing values and the intermediate value into a new array as you go:

    const arr = [0, 4, 10, -20, 10, 20, 50];
    
    const res = [];
    arr.forEach((v, i) => {
      if (i != 0) res.push((v + arr[i - 1]) / 2);
      res.push(v);
    });
    
    console.log(res);

    You could also use flatMap, creating both entries at once by mapping the array and then flattening the result:

    const arr = [0, 4, 10, -20, 10, 20, 50];
    
    const res = arr.flatMap((v, i) => i == 0 ? v : [(v + arr[i - 1]) / 2, v]);
    
    console.log(res);

    You could also (as suggested by Som in the comments), ignore the array indexing issue when i == 0 and just slice off the NaN value that is generated:

    const arr = [0, 4, 10, -20, 10, 20, 50];
    
    const res = arr.flatMap((v, i) => [(v + arr[i - 1]) / 2, v]).slice(1);
    
    console.log(res);