Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Прошу подсказки отсортировать объекты (https://javascript.ru/forum/misc/77752-proshu-podskazki-otsortirovat-obekty.html)

Sergius182 15.06.2019 21:37

Прошу подсказки отсортировать объекты
 
Есть к примеру такие вот объекты- список машин с свойствами.
Как отсортировать их? - нажал на кнопку "сорт по пробегу"- получил список со всеми характеристиками сначала больший пробег потом меньший, также с массой и длиной


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title>  </head> <body><h4>
<button onclick="sortProbeg()">По пробегу</button>
<button onclick="sortMas()">По массе</button>
<button onclick="sortDl()">По длинне</button>

<div id="di">Отсортированные объекты</div>
<script>

// конструктор
function car(carColor,probeg,massa,dlina) {
	   this.carColor= carColor;
	   this.probeg= probeg;
	   this.massa= massa;
	   this.dlina= dlina;
 };
 
// создаем по конструктору несколько объектов
 var renault= new car ("green", 110000, 1165, 4346);
 var toyota= new car ("red", 155000, 1274, 4540);
var peugeot= new car ("blue", 90000, 1156, 4132);

  
</script>

</h4></body>
</html>

рони 15.06.2019 21:45

Sergius182,
создайте массив, отсортируйте элементы по нужному свойству.

Sergius182 15.06.2019 21:53

у меня получилось отсортировать массив, но при выводе на экран нужно вывести полную инфу о объекте - т.е. из других массивов соответствующую информацию, как это можно сделать?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" /> <meta name="description" content="" /> <meta name="keywords" content="" /> </head> <body><h1>
<button onclick="f()">Сортировка</button>
<div id="di"></div>


<script>
var MassivProbeg= [23,43,55,57]
var MassivKM= [13,103,40,56]
var MassivProbeg= [23.4,43.4,54.4,56.4]

function f( ) { 

di.innerHTML= MassivKM.sort(function(a,b){return a-b})
}

</script>


</h1></body>
</html>

рони 15.06.2019 21:54

Sergius182,
https://javascript.ru/forum/dom-wind...tml#post500746

рони 15.06.2019 22:08

сортировка массива обьектов es6
 
:)
function Car(color, mileage, weight, length) {
            this.color = color;
            this.mileage = mileage;
            this.weight = weight;
            this.length = length;
        };
        // создаем по конструктору несколько объектов
        const cars = [
            new Car("green", 110000, 1165, 4346),
            new Car("red", 155000, 1274, 4540),
            new Car("blue", 90000, 1156, 4132),
        ];

        const carsSorted = (cars,key, reverse) => Array.from(cars).sort(({ [key]: a }, { [key]: b }) => reverse ? b - a : a - b);
        console.log("cars sorted by mileage", carsSorted(cars,"mileage"));
        console.log("cars sorted by weight", carsSorted(cars,"weight"));
        console.log("cars sorted by length", carsSorted(cars,"length", true));

Sergius182 15.06.2019 22:30

Спасибо, но у меня не выходит что то , видимо надо еще учебник почитать, не сортируется ..

Malleys 15.06.2019 22:54

<!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>

рони 15.06.2019 22:56

Цитата:

Сообщение от Sergius182
но у меня не выходит что то

лучше код и описание проблемы.

рони 15.06.2019 23:05

Цитата:

Сообщение от Malleys
const index = [...target.parentNode.cells].indexOf(target);

как вариант ...
const {cellIndex : index} = target;


Часовой пояс GMT +3, время: 07:38.