Problems With Reduce Function

不问归期 提交于 2021-02-05 08:48:05

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/50195003/problems-with-reduce-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!