1

I have been trying to create an example problem for testing out the reduce function in javascript. the program it is intended to a single object from a set of input lines.

function generateInputs(){
  var inputLines = Math.floor(Math.random() * 100)

  var arr = [];

  arr[0] = inputLines;

  var userIDs = ["a","b","c","d","e"]

  for(i=0; i<inputLines; i++){
      let userID = userIDs[Math.floor(Math.random() * userIDs.length)]
      let usage = Math.floor(Math.random(600))

      arr.push(userID + " " + usage)
  }
  return arr;
}

let inputs = generateInputs()

function parseInput(line){
  return line.split(" ");
} 

let list = inputs.reduce(function(accumulator,inputLine){
    if(typeof inputline === "string"){
        let parsedInput = parseInput(inputLine);
        accumulator[parsedInput[0]] = parsedInput[1];     
    }
}, {})

console.log(list)

it keeps returning undefined and I have been through it several times. the only thing I have found it a problem with the "if" statement which I wasn't able to remedy. do you see any solutions?

Leviathan_the_Great
  • 429
  • 1
  • 5
  • 14
  • 1
    You're not `return`ing the accumulator after the `if`. – 4castle May 05 '18 at 23:47
  • why does the return statement have to be after the if statement, if I may ask? because I tried to return the accumulator in the if statement and it didn't work. I think there is something about the syntax that I am missing:/ – Leviathan_the_Great May 06 '18 at 04:00
  • 1
    If you put the return statement inside the if, then your function will implicitly return `undefined` when the if statement doesn't execute. There needs to be a `return` statement for every branch of the code, or else the `accumulator` will get set to `undefined` on the next iteration. – 4castle May 06 '18 at 05:38

1 Answers1

3

You have to return the accumulator (or return something different depending on use case) in reduce() callback.

Otherwise the next iteration of the reduce loop accumulator will be undefined

charlietfl
  • 170,828
  • 13
  • 121
  • 150