The sort() function in p5.js is used to sort the array elements. If the array elements are strings then it sorts them alphabetically and if the array elements are integers then it sorts them in increasing order.
Syntax:
sort(Array, Count)
Parameters: This function accepts two parameters as mentioned above and described below:
- Array: This parameter holds the array elements which to be sorted.
- Count: It holds the number of elements which need to be sorted. This should be less than the length of the array.
Return Value: It returns a new sorted array.
Below programs illustrates the sort() function in p5.js:
Example 1: This example uses sort() function to sort the array elements.
function setup() {
createCanvas(500, 90);
}
function draw() {
background(220);
let Array = [ 'IT' , 'CSE' , 'ECE' , 'CIVIL' ];
let Count = 3;
let A = sort(Array, Count);
textSize(16);
fill(color( 'red' ));
text( "New sorted array is : " + A, 50, 30);
}
|
Output:
Example 2: This example uses sort() function to sort the array elements.
function setup() {
createCanvas(500, 90);
}
function draw() {
background(220);
let Array = [ 'IT' , 'CSE' , 'ECE' , 'CIVIL' ];
let Count = 4;
let A = sort(Array, Count);
textSize(16);
fill(color( 'red' ));
text( "New sorted array is : " + A, 50, 30);
}
|
Output:
Example 3: This example uses sort() function to sort the array elements.
function setup() {
createCanvas(500, 90);
}
function draw() {
background(220);
let Array = [9, 6, 0, 22, 4, 1, 15];
let Count = 5;
let A = sort(Array, Count);
textSize(16);
fill(color( 'red' ));
text( "New sorted array is : " + A, 50, 30);
}
|
Output:
Reference: https://p5js.org/reference/#/p5/sort
Last Updated :
22 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...