1

I am calculating max and min value from array of integer using JavaScript but as per my code the wrong value is coming. I am explaining my code below.

const arr = [1, 2, 3, 4, 100];

const arr1 = arr.reduce((a,i) => {
  let max = a > i ? a:i;
  let min = a < i ? a:i;
  return {max: max, min: min};
},{})

console.log(arr1);

Here I am getting both max and min value as 100. Here I need to return max and min value from array.

1
  • 1
    you're comparing an object {} to your integer (always false), which does not meaningfully get the min max. what you should have been doing is comparing your object's min property to i Commented Jun 17, 2020 at 6:17

3 Answers 3

1

If you want to do it with reduce this is the answer:

const arr = [1, 2, 3, 4, 100];

const arr1 = arr.reduce((a,i) => {
  let max = a.max > i ? a.max:i;
  let min = a.min < i ? a.min:i;
  return {max, min};
},{})

console.log(arr1);
Sign up to request clarification or add additional context in comments.

Comments

1

Just use Math.max() and Math.min()

const arr = [1, 2, 3, 4, 100];

var max = Math.max(...arr);

var min = Math.min(...arr);

console.log({max, min});

Comments

0

You could destructure min and max, check each with the actual value, adjust if necessary and return a new object with short hand properties.

As start object, you need some really large values.

const
    array = [1, 2, 3, 4, 100],
    minMax = array.reduce(({ min, max }, value) => {
        if (min > value) min = value;
        if (max < value) max = value;
        return { min, max };
    }, { min: Infinity, max: -Infinity });

console.log(minMax);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.