DEV Community

Rae Liu
Rae Liu

Posted on

2D array peak - JS (reduce function)

I have taken couple days to learn what is Reduce, UseReducer functions (JS, React) so I was thinking maybe I can find something fun to code.

No small chat, here is the question -

2-D Peak Finding

 - c - - -
 c - e - z
 - r s u x
 - r - a z

In the 2d array depicted above, a is a peak, if a >= b, a >= d, a >= e, a >= c, find the peak array.

Output should be 'a'

var arr = [ [ '', 'c', '', '',''], 
        [ 'c', '', 'e', '','z' ], 
        [ '', 'r', 's', 'u', 'b' ], 
        [ '', 'h', '', 'a','z' ] ];
Enter fullscreen mode Exit fullscreen mode

1. How to compare

'a'>'b' === false , 'b' > 'a' === true

2. Loop

We split the matrix row by row, and then find the peak for each row.
We know the min is z

console.log(array.reduce(findPeak, 'z'));

//split row by row
const findPeak = (currPeak, currRow) =>{
  //currRow is still an array
  //So use reduce function again
  //currRow.reduce(findPeakPerRow, 'z')
}

const findPeakPerRow = (currPeak, currEle) =>{
  //Compare currPeak and CurrEle
}
//compare function
const getMaxValue = (currPeak, currValue) => {
  //if currValue is not an array, then find the max value
  return (currValue && currValue < currPeak ? currValue : currPeak)
}
Enter fullscreen mode Exit fullscreen mode

Full Codes -

const findPeak = (currPeak, currRow) =>{
  let currValue = currRow.reduce(findPeakPerRow, 'z');
  return (getMaxValue(currPeak, currValue));
}

const findPeakPerRow = (maxValue, currValue) => {
  return (getMaxValue(maxValue, currValue));
}

const getMaxValue = (currPeak, currValue) => {
  return (currValue && currValue < currPeak ? currValue : currPeak)
}

console.log(arr.reduce(findPeak, 'z'))
Enter fullscreen mode Exit fullscreen mode

3. Recursive Function?

Not sure if we can convert those to recursive functions...
Feel free to comment any ideas!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay