Leviathan_the_Great
Leviathan_the_Great

Reputation: 448

Problems With Reduce Function

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?

Upvotes: 1

Views: 171

Answers (1)

charlietfl
charlietfl

Reputation: 171698

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

Upvotes: 3

Related Questions