Home > OS >  why a double implementation of reducer method returns NAN when trying to find the second larger numb
why a double implementation of reducer method returns NAN when trying to find the second larger numb

Time:11-16

So, I did this in order to find the second biggest value in an array (I know there are a lot of answers out there, I just want to know why this approach fails)

With a first reduce() method on the number array I find the largest number, then using a second reduce() method I tried to use an if statement to check return the biggest number only if the compared numbers are not the previous biggest one found. This is the code:

const arr = [1,6,2,7,3,9,5,8];

const biggest = arr.reduce((a,b)=> {
  return Math.max(a,b)
})

console.log(biggest)

const secondBiggest = arr.reduce((a,b)=>{
  if(a!= biggest && b!= biggest){
    return Math.max(a,b)
  }
})

console.log(secondBiggest) // --> NAN
 

CodePudding user response:

In every iteration you need to return something from reduce function. so currently you just return when (a!= biggest && b!= biggest) is true. so you need to return the original value of accumulator a when the condition doesn't match as well (return a).

Learn more about reduce()

const arr = [1,6,2,7,3,9,5,8];

const biggest = arr.reduce((a,b)=> {
  return Math.max(a,b)
})

console.log(biggest)

const secondBiggest = arr.reduce((a,b)=>{
  if(a!= biggest && b!= biggest){
    return Math.max(a,b)
  }
  return a; // if you don't return anything during the next iteration the accumulator will have `undefined`.  
})

console.log(secondBiggest) // --> NAN

CodePudding user response:

You want return your accumulator as is if the current one is the biggest

const arr = [1, 6, 2, 7, 3, 9, 5, 2];

const biggest = Math.max([...arr])

console.log(biggest)

const secondBiggest = arr.reduce((accumulator, current) => {
  if (current != biggest) {
    return Math.max(accumulator, b)
  }
  return a
})

console.log(secondBiggest)

  • Related