The d3.scan() function is a built-in function in D3.js which scans the array linearly and returns the index of the minimum element according to the specified comparator. The function returns undefined when there are no comparable elements in the array.
Syntax:
d3.scan(array, comparator)
Parameters: This function accepts two parameters which are mentioned above and described below:
- array: This mandatory parameter contains an array of elements whose minimum value is to be calculated and the respective index is to be returned.
- comparator: This parameter is an optional parameter which specifies how the minimum element is to be obtained.
Return value: The function returns a single integer value denoting the index of the minimum element in the array based on the specified comparator.
The below programs illustrate the use of d3.scan() function:
Example 1: This program illustrates the use of d3.scan() with a comparator
<!DOCTYPE html> < html > < head > < title >D3.js d3.scan() Function</ title > </ head > < body > < script > var array = [42, 71, 91, 67, 43, 17, 53]; // To obtain the minimum element in the array var ans1 = d3.scan(array, function(a, b) { return a - b; }); document.write("Minimum element is " + array[ans1] + " present at index: " + ans1 + "< br >"); // To obtain the maximum element in the array var ans2 = d3.scan(array, function(a, b) { return b - a; }); document.write("Maximum element is " + array[ans2] + " present at index: " + ans2); </ script > </ body > </ html > |
Output:
Minimum element is 17 present at index: 5 Maximum element is 91 present at index: 2
Example 2: This program illustrate the use of d3.scan() without a comparator
<!DOCTYPE html> < html > < head > < title >D3.js d3.scan() Function</ title > </ head > < body > < script > var array = [42 , 71 , 91 , 67 , 43 , 17 , 53]; // To obtain the minimum element in the array var ans1 = d3.scan(array, ); document.write("Minimum element is " + array[ans1] + " present at index: " + ans1); </ script > </ body > </ html > |
Output:
Minimum element is 17 present at index: 5
Reference:https://devdocs.io/d3~5/d3-array#scan