The maxValue() method of p5.NumberDict in p5.js is used to find the highest value in a number dictionary. A number dictionary can store multiple key-value pairs.
Syntax:
maxValue()
Parameters: This method does not accept any parameters.
Return Value: It returns a Number value that is the highest value in the dictionary.
The example below illustrates the maxValue() method in p5.js:
Example:
function setup() {
createCanvas(550, 300);
textSize(16);
text( "Click on the button to create a new " +
"dictionary and get the highest value" ,
20, 20);
setBtn =
createButton( "Create random dictionary" );
setBtn.position(30, 40);
setBtn.mouseClicked(createNewDict);
getBtn =
createButton( "Get highest Value" );
getBtn.position(300, 40);
getBtn.mouseClicked(getHighestValue);
} function createNewDict() {
clear();
// Create an object with random values
let obj = {};
for (let i = 0; i < 5; i++) {
let rk = ceil(Math.random() * 100);
let rn = floor(Math.random() * 100);
rn = (rk > 25) ? rn : -rn;
obj[rk] = rn;
text( "Key: " + rk + " : Value: " +
rn, 40, 120 + 20 * i);
}
// Create a dictionary using the above values
numDict = createNumberDict(obj);
text( "New Dictionary created with values" ,
20, 80);
text( "Click on the button to create a new " +
"dictionary and get the highest value" ,
20, 20);
} function getHighestValue() {
// Get the highest value in the dictionary
let highestVal = numDict.maxValue();
// Display the highest value
text( "The highest value in the dictionary is: " +
highestVal, 20, 240);
text( "Click on the button to create a new " +
"dictionary and get the highest value" ,
20, 20);
} |
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/
Reference: https://p5js.org/reference/#/p5.NumberDict/maxValue