1

I am trying to play with the Reduce function in JavaScript. What I am trying to achieve can be easily done via the filter function but I am trying to do it via Reduce.

I am trying to retrieve all the people where the age is greater or equal to 18 years and store the result in an array

var people = [
{ name: "John", age: 16 },
{ name: "Thomas", age: 20 },
{ name: "Smith", age: 18 },
{ name: "Jessy", age: 17 },
];
var arr = [];
var output = people.reduce(function(arr,ppl){
if(ppl.age >= 18)
    return(arr.push(ppl));
},arr);
console.log(output);

However when I run this snippet, I get an error that says "TypeError: Cannot read property 'push' of undefined". I am not sure where do I need to define the arr (array where I need to store the output)

Manish
  • 21
  • 5

3 Answers3

1

try this:

you should return arr,not return arr.push(ppl) because [].push(3) return 1(new length of [] ) not [3].And reduce works with accumulator which in this case the accumulator is arr.So,you should return arr not return (arr.push(ppl));

var people = [{
    name: "John",
    age: 16
  },
  {
    name: "Thomas",
    age: 20
  },
  {
    name: "Smith",
    age: 18
  },
  {
    name: "Jessy",
    age: 17
  },
];
var arr = [];
var output = people.reduce(function(arr, ppl) {
  if (ppl.age >= 18)
    (arr.push(ppl));
  return arr;

}, arr);
console.log(output);
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0
 return(arr.push(ppl));

As arr.push returns the new length of the array, it will return a number. So at the next iteration arr will be a number, and you cant push to that. So you need to pass on the array:

 const output = people.reduce((arr, person) => person.age > 17 ? arr.concat(person): arr, []);

That works as arr.concat returns an array.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You can use array.concat to push to an array and return it, and put that in a ternary operator:

let people=[{name:"John",age:16},{name:"Thomas",age:20},{name:"Smith",age:18},{name:"Jessy",age:17}]

let output = people.reduce((arr,ppl) => {
    return ppl.age >= 18 ? arr.concat(ppl) : arr
},[])

console.log(output)
symlink
  • 11,984
  • 7
  • 29
  • 50