JSFiddle - React, Tailwind, and code Playground
JavaScript
// Array Of Cities
var countries = [
{
"country": "Indonesia",
"city": "Jakarta",
"population": 30539
},
{
"country": "India",
"city": "Delhi",
"population": 24998
},
{
"country": "Philippines",
"city": "Manila",
"population": 24123
},
{
"country": "Japan",
"city": "Tokyo",
"population": 37843
},
{
"country": "The Republic of Korea",
"city": "Seoul",
"population": 23480
},
{
"country": "China",
"city": "Shanghai",
"population": 23416
},
{
"country": "Pakistan",
"city": "Karachi",
"population": 22123
},
{
"country": "China",
"city": "Beijing",
"population": 21009
},
{
"country": "USA",
"city": "New York City",
"population": 20630
},
{
"country": "China",
"city": "Guangzhou",
"population": 20597
}
];
// Input N number
var numberOfCity = +prompt("Enter the number of cities to print in console");
// Check input to number
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// Sort by population
function sortCitiesPopulation(a, b) {
if (a.population > b.population) return -1;
if (a.population < b.population) return 1;
if (a.population === b.population) return 0;
}
// Print N cities in console
function printList(numberOfCity, arrayToPrint) {
for (var i = 0; i < numberOfCity; i++) {
console.log("Country: " + arrayToPrint[i].country + " City: " + arrayToPrint[i].city + " Population: " + arrayToPrint[i].population);
}
}
if (isNumeric(numberOfCity) && numberOfCity > 0) {
countries.sort(sortCitiesPopulation);
printList(numberOfCity, countries);
} else {
alert("You must enter number > 0!");
}