Baam
Baam

Reputation: 13

Problem finding the largest element in an array

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.

Upvotes: 1

Views: 53

Answers (2)

Taimoor Qureshi
Taimoor Qureshi

Reputation: 630

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

Upvotes: 0

user8082655
user8082655

Reputation:

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]))

Upvotes: 1

Related Questions