Search code examples
google-apps-scriptarraylistnumberssmoothing

Add average smooth numbers inside an array of numbers


Need google app script to smoothen an aaray of numbers with adding extra smoothining numbers with multiple factors in that array by using for loop. Example suppose the array is- myarray = ["1", "4"," 2", "1","5"," 2"]; and the multiple factor is 1 then the smoothening array of numbers should be as - (1),2,3,(4),,3,(2),(1),2,3,4,(5),4,3,(2). In the new array the numbers in bracket are the numbers as in myarray[] and the numbers not within bracket are smoothening numbers need to be add in the new smoothening array. The logic is every recent item is divided by multiple factor and should add to the previous item with the quotient till <= to the recent item. Like In myarray[] suppose the multiple factor is 2 then the new array should be -(1), 3,(4),(2),(1),3,(5),3,(2). Here the second recent item in myarray[] is 4, so 4 is divided by multiple factor 2 and the quotient 2 is add with previous item 1 in my array[] till <= to recent item and do so in sequence so that the new array made with adding smoothening numbers.


Solution

  • Smoothy

    function smoooth() {
      const arr = [1, 4, 2, 1, 5, 2];//original array
      const sa = [];
      arr.forEach((v, i, a) => {
        let incr = a[i + 1] > v ? 1 : -1;
        let n = Math.abs(a[i + 1] - v) - 1;
        sa.push(v);
        if (!isNaN(n)) {
          [...Array.from(new Array(n).keys())].forEach(x => {
            sa.push(sa[sa.length - 1] + incr);
          });
        }
      });
      Logger.log(JSON.stringify(sa));
      return sa;
    }