Handsontable example
by handsoncode
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.css">
<script src="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.js"></script>
<div id="example1" class="handsontable"></div>
CSS
body {
background: white;
margin: 0;
padding: 0;
font-size: 0.9em
}
JavaScript
var data = [{
country: 'Germany',
city: 'Berlin',
distance: '878.442 km'
}, {
country: 'England',
city: 'London',
distance: '343.934 km'
}, {
country: 'Romania',
city: 'Bucharest',
distance: '1163.444 miles'
}, {
country: 'Poland',
city: 'Warsaw',
distance: '850.085 miles'
}, {
country: 'Norway',
city: 'Oslo',
distance: '1343.478 km'
}, {
country: 'Spain',
city: 'Madrit',
distance: '654.972 miles'
}, {
country: 'Iran',
city: 'Teheran',
distance: '4215.403 km'
}, {
country: 'Russia',
city: 'Moscow',
distance: '2489.031 km'
}];
var
container = document.getElementById('example1'),
hot = new Handsontable(container, {
data: data,
licenseKey: 'non-commercial-and-evaluation',
width: 745,
colWidths: [245, 200, 300],
colHeaders: ['Country', 'City', 'Distance'],
columnSorting: true,
sortIndicator: true,
columns: [{
data: 'country'
}, {
data: 'city',
}, {
data: 'distance',
sortFunction: function(sortOrder) {
// Handsontable's object iteration helper
var objectEach = Handsontable.helper.objectEach;
var unitsRatios = {
'km': 1,
'miles': 1.609
};
var parseUnit = function(value, unit, ratio) {
if (isNaN(value) && value.indexOf(' ' + unit) > -1) {
value = parseFloat(value.replace(unit, '')) * ratio;
}
return value;
};
return function(a, b) {
var newA = a[1];
var newB = b[1];
objectEach(unitsRatios, function(val, prop) {
newA = parseUnit(newA, prop, val);
newB = parseUnit(newB, prop, val);
});
if (newA < newB) {
return sortOrder ? -1 : 1;
}
if (newA > newB) {
return sortOrder ? 1 : -1;
}
return 0;
}
}
}]
});