D3.js is a library built with JavaScript and particularly used for data visualization. The nest.sortKeys() function is used to sort the keys in a particular order i.e. ascending or descending.
Syntax:
nest.sortkeys( comparatorFunction )
Parameters: This function accepts a single parameter comparatorFunction that is used to specify how to sort the keys. If no comparatorFunction is specified for the current key, the order in which keys will be returned is not defined.
Return Value: It returns the sorted key (ascending/descending) according to comparator function.
Below programs illustrate the nest.sortKeys() function in D3.js.
Example 1:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" path1tent = "width=device-width, initial-scale=1.0" > </ script > < title > D3.js nest.sortKeys() Function </ title > </ head > < body > < script > // Dataset var cars = [ { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1952", model: "s51" }, { name: "car1", manufactured: "1951", model: "s50" }, { name: "car1", manufactured: "1953", model: "s52" }, { name: "car1", manufactured: "1953", model: "s50" }, { name: "car1", manufactured: "1950", model: "s52" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) // sorting keys in ascending order .sortKeys(d3.ascending) .entries(cars); console.log("ArrayData :", groupedData); </ script > </ body > </ html > |
Output:
Example 2:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" path1tent = "width=device-width, initial-scale=1.0" > </ script > < title > D3.js nest.sortKeys() Function </ title > </ head > < body > < script > var cars = [ { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1952", model: "s51" }, { name: "car1", manufactured: "1951", model: "s50" }, { name: "car1", manufactured: "1953", model: "s52" }, { name: "car1", manufactured: "1953", model: "s50" }, { name: "car1", manufactured: "1950", model: "s52" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) // Sorting keys in descending order .sortKeys(d3.descending) .entries(cars); console.log("ArrayData :", groupedData); </ script > </ body > </ html > |
Output: