I dont get it... why he used obj in this function, can someone explain what it doing.
const yourArray = [37, 32,97,35,76,62] function equalizeArray(arr) { let obj = {}, max = 1 arr.forEach(el => { if (obj.hasOwnProperty(el)) { obj[el] = obj[el] + 1; if (obj[el] > max) { max = obj[el]; } } else{ obj[el] = 1 } }) return arr.length - max } console.log(equalizeArray(yourArray));
From what I gather, the function's purpose is to count the maximum number of same values in an array, and then subtract that maximum number ( max
) from the array's length and return that.
The function uses an object obj
to store array values as keys, and their repetition count as values to those keys.
The variable max
keeps track of the maximum repetition, if any key has a value bigger than max
it gets reassigned.
And then function returns array.length - max
.
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.