var data = [
{'city': 'Джакарта', 'country': 'Индонезия', 'population': 30539, 'area': 3225, 'density': 9500 },
{'city': 'Каир', 'country': 'Египет', 'population': 25600, 'area': 1761, 'density': 15105 },
{'city': 'Карачи', 'country': 'Пакистан', 'population': 25423, 'area': 945, 'density': 26902 },
{'city': 'Токио', 'country': 'Япония', 'population': 37843, 'area': 8547, 'density': 4400 },
];
function sortTable(sortByField, sortType, limit) {
var result = data.sort(getSortCallbackFor(sortByField, sortType));
if (!Number.isInteger(limit) || limit < 0) {
return result;
}
return result.slice(0, limit);
}
function getSortCallbackFor(field, order) {
var resultCallback;
if (['city', 'country'].indexOf(field) >= 0) {
if (order === 'ASC') {
resultCallback = function(a, b) {
return a[field].localeCompare(b[field]);
}
} else if (order === 'DESC') {
resultCallback = function(a, b) {
return b[field].localeCompare(a[field]);
}
} else {
throw new Error('Invalid order');
}
} else if (['population', 'area', 'density'].indexOf(field) >= 0) {
if (order === 'ASC') {
resultCallback = function(a, b) {
return a[field] - b[field];
}
} else if (order === 'DESC') {
resultCallback = function(a, b) {
return b[field] - a[field];
}
} else {
throw new Error('Invalid order');
}
} else {
throw new Error('Invalid field');
}
return resultCallback;
}
// Тесты
var tableSorted1 = sortTable('population', 'DESC', 3);
console.log(tableSorted1.length === 3);
console.log(tableSorted1[0].city === 'Токио');
console.log(tableSorted1[1].city === 'Джакарта');
console.log(tableSorted1[2].city === 'Каир');
var tableSorted2 = sortTable('country', 'ASC');
console.log(tableSorted2.length === 4);
console.log(tableSorted2[0].country === 'Египет');
console.log(tableSorted2[1].country === 'Индонезия');
console.log(tableSorted2[2].country === 'Пакистан');
console.log(tableSorted2[3].country === 'Япония');
dmFyIGRhdGEgPSBbCgl7J2NpdHknOiAn0JTQttCw0LrQsNGA0YLQsCcsICdjb3VudHJ5JzogJ9CY0L3QtNC+0L3QtdC30LjRjycsICdwb3B1bGF0aW9uJzogMzA1MzksICdhcmVhJzogMzIyNSwgJ2RlbnNpdHknOiA5NTAwIH0sCgl7J2N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