<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
cursor: default;
table-layout: fixed;
}
thead * {
cursor: pointer;
user-select: none;
}
thead .sorted[data-order="-1"]::after {
content: "▼"
}
thead .sorted[data-order="1"]::after {
content: "▲"
}
th,
td {
text-align: left;
padding: 16px;
}
tbody tr:nth-child(odd) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<h4>Отсортированные объекты</h4>
<script>
function Car(name, color, mileage, weight, length) {
this.name = name;
this.color = color;
this.mileage = mileage;
this.weight = weight;
this.length = length;
};
// создаем по конструктору несколько объектов
const cars = [
new Car("renault", "green", 110000, 1165, 4346),
new Car("toyota", "red", 155000, 1274, 4540),
new Car("peugeot", "blue", 90000, 1156, 4132),
];
function createCarsTable(cars) {
var row, cell;
const properties = [{
name: "name",
i18n: { ru: "Имя" }
}, {
name: "color",
i18n: { ru: "Цвет" }
}, {
name: "mileage",
i18n: { ru: "Километраж" }
}, {
name: "weight",
i18n: { ru: "Вес" }
}, {
name: "length",
i18n: { ru: "Длина" }
}];
const table = document.createElement("table");
const tHead = table.createTHead();
row = tHead.insertRow();
properties.forEach(p => {
cell = row.insertCell();
cell.textContent = p.i18n.ru;
cell.tabIndex = 0;
});
const tBody = table.createTBody();
for (const car of cars) {
row = tBody.insertRow();
properties.forEach(p => {
cell = row.insertCell();
cell.textContent = car[p.name];
});
}
function sortByColumn({ target }) {
const order = (target.dataset.order = -(target.dataset.order || -1));
const { cellIndex: index } = target;
const collator = new Intl.Collator(["en", "ru"], {
numeric: true
});
const comparator = (index, order) => (a, b) => order * collator.compare(
a.children[index].textContent,
b.children[index].textContent
);
for(const tBody of target.closest("table").tBodies)
tBody.append(...[...tBody.rows].sort(comparator(index, order)));
for(const cell of target.parentNode.cells)
cell.classList.toggle("sorted", cell === target);
}
tHead.addEventListener("click", sortByColumn);
tHead.addEventListener("keyup", sortByColumn);
return table;
}
document.body.appendChild(createCarsTable(cars));
</script>
</body>
</html>