简体   繁体   中英

Return the biggest number in the array (array contains a string)?

I dont understand why my code is not working, when I read it logically I feel that it should work, but what it does is return 3,4,2 as opposed to the highest number of the 3 (ie 4)

const array2 = ['a', 3, 4, 2] // should return 4

for(items of array2){
    if(items > 0) {
        console.log(Math.max(items));
}

What am I doing wrong? What have I misinterpreted? Please don't give me the answer, just tell me why my logic does'nt work

in for-loop, items is just one item actually. Each time, you print the current item. it is basically the same thing with this

const array2 = ['a', 3, 4, 2] // should return 4

for(items of array2){
    if (items > 0) {
        console.log(items);
    }
}

you can do it with this only

const array2 = ['a', 3, 4, 2] // should return 4

console.log(Math.max(...array2.map(s => +s || Number.MIN_SAFE_INTEGER)));

check out: https://stackoverflow.com/a/44208485/16806649

if it was integer-only array, this would be enough:

const array2 = [3, 4, 2] // should return 4

console.log(Math.max(...array2));

I don't think you need the "For(items of arr)" instead just if the length of the array is greater than 0, then console.log(Math.max(...arr) should work.

See document ion below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

  • You just need to filter the array.
  • Below example I am using filter() method of array and then just pass that filteredarray to Math.max() function.
  • isNan() function returns false for valid number.
  • Math.max(...filteredArr) is using spred operator to pass the values.

 const arr = ['a', 3, 4, 2]; const filteredArr = arr.filter(val => { if (;isNaN(val)) return val. }) console.log(Math.max(..;filteredArr));

It is returning 3,4,2 because you are taking array2, and iterating through with each individual element of the array. items is not the entire array, it is the individual element and that is why Math.max of an individual element is just getting the same value.

just you need fliter you're array then get max value, also in arrayFilters function use to removes everything only return numbers of this array

 function arrayFilters(array){ const number = array.filter(element => typeof element === 'number') return number; } function getMaxValue(number){ return Math.max.apply(null,number) } const arr = ['a',2,3,4]; console.log(getMaxValue(arrayFilters(arr)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM