1

I'm trying to write a function that receives a string of integers -I know this is not the ideal but it is how I was asked to do in an exercise-, puts them into an array an then gets the max value, minimal value, reads the entire array and counts how many times the max value was surpassed, and for last gives the position of the minimal value.

This is my code:

function performance(string) {

    let arrayScore = string.split(' ') //this part works as I tested before, the numbers of the string are correctly passed to the array

    let max = arrayScore[0]
    let min = arrayScore[0]

    let worstgame = 1
    let surpasses = 0

    for (let i = 0; i < arrayScore.length; i++) {

        if (max < arrayScore[i]) {

            max = arrayScore[i]
            surpasses++
        }

        if (min > arrayScore[i]) {

            min = arrayScore[i]
            worstgame = i + 1
        }
    }

    //max = arrayScore.reduce((a, b) => Math.max(a, b))
    //min = arrayScore.reduce((a, b) => Math.min(a, b))

    return [surpasses, worstgame, max, min]
}

let score = "10 20 20 8 25 3 0 30 1"

console.log(performance(score)) /*here is the problem: the value 8 is attributed to 'max' -should be 30- and the number of surpasses returns 2 -should be 3-*/

I noticed that I can get the max value by using Math.max as an argument in reduce, but I still don't understand why counting the surpasses and the "if" condition for "max" in the "for" loop are not working.

3

2 Answers 2

1

You compare numbers as strings, so '30' < '8' returns true :). Just use Number.parseInt() in order to get a number from a string (e.g. Number.parseInt(max) < Number.parseInt(arrayScore[i]))

Sign up to request clarification or add additional context in comments.

2 Comments

Always supply a radix when using parseInt - from the docs: Be careful—this does not default to 10!
It's just easier to use the + operand here. string.split(' ').map(Number) is also more convenient.
0

how you can do that

function performance(str) {
let scoreArr = str.split(' ').map(data => Number(data))
  return scoreArr.reduce((max, num) => {
           return max > num ? max : num; 
},0)
}

let score = "10 20 20 8 25 3 0 30 1"

console.log(performance(score))
// 30

1 Comment

If it's just a few numbers (~ fewer than thousands) you can use Math.max(...str.split(' ').map(Number)

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.