Anna Lee
Anna Lee

Reputation: 951

run into Cannot read property 'push' of undefined in lodash's reduce function

I am beginner using reduce function and lodash library, I am trying to have array referred to as result here, but I run into some situation like below.

          let result: Array<number> = [];
            result.push(1); // [1]

            _.reduce(array, function(result, el, idx) {
                if(el.node === array[child_index].parent) {
                    result.push(parseInt(idx)); // [2]
                    return result; 
                }
            }, result);

Could I ask why I was able to push the value at [1] while I was not able to push the value at [2], Actually, I run into this error message in [2]. TypeError: Cannot read property 'push' of undefined, I am using lodash for reduce function. I also tried concat it returned same error. If anyone had same issues, could I get some advice for this?

Upvotes: 0

Views: 614

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44115

You need to return result as a default action to prevent the error if the if statement is not true:

_.reduce(array, function(result, el, idx) {
  if (el.node === array[child_index].parent) {
    result.push(parseInt(idx));
  }
  return result;
}, result);

Upvotes: 1

Related Questions