Home > Software design >  How to subtract using a reduce function?
How to subtract using a reduce function?

Time:11-15

I am doing this exercise from the book Eloquent JavaScript and I am trying to subtract a list using the reduce function and show the sum at the end. This is what I have:

function getRange(start, end, step) {
  let arraylist = [];
  if (start < end) {
    for (let i = start; i <= end; i  = step) {
      arraylist.push(i);
    }

    let sum = arraylist.reduce(function(accumulator, n) {
      return accumulator   n;
    }, 0);

    return arraylist.join("   ")   " = "   sum;
  } else {
    for (let i = start; i >= end; i  = step) {
      arraylist.push(i);
    }

    let sum2 = arraylist.reduce(function(accumulator, n) {
      return accumulator - n;
    }, 0);

    return arraylist.join(" - ")   " = "   sum2;
  }
}

console.log(getRange(10, 5, -1));

this is what I get when I run the code.

CodePudding user response:

Here you can try this logic :

let arr = [10, 9, 8, 7, 6, 5];
let sum = 0;
let dash = "";
let result = arr.reduce((prev, curr, index, arr) => {
  prev = prev   dash   curr;
  sum -= curr;
  dash = "-";
  return prev;
}, "");

console.log(result   " = ", sum);

CodePudding user response:

I hope this will help you,

function getRange(start, end, step) {
  let arraylist = [];
  if (start < end) {
    for (let i = start; i <= end; i  = step) {
      arraylist.push(i);
    }

    const sum = arraylist.reduce(
      (previousValue, currentValue) => previousValue   currentValue
    );

    return arraylist.join("   ")   " = "   sum;
  } else {
    for (let i = start; i >= end; i  = step) {
      arraylist.push(i);
    }
    
    const sum2 = arraylist.reduce(
      (previousValue, currentValue) => previousValue - currentValue
    );

    return arraylist.join(" - ")   " = "   sum2;
  }
}

console.log(getRange(10, 5, -1));

  • Related