sort
?const tickets = [
{from: 'Sochi', to: 'Paris'},
{from: 'Moscow', to: 'Sochi'},
{from: 'London', to: 'Moscow'},
{from: 'Berlin', to: 'Kamchatka'},
{from: 'Paris', to: 'Berlin'},
]
function sortTickets(tickets ) {
return tickets.sort((a, b) => {
return a.from === b.to
})
}
0: {from: 'London', to: 'Moscow'}
1: {from: 'Moscow', to: 'Sochi'}
2: {from: 'Sochi', to: 'Paris'}
3: {from: 'Paris', to: 'Berlin'}
4: {from: 'Berlin', to: 'Kamchatka'
from
, но отсутствует в to
. От него пляшем по цепочке, добавляя инкрементируемое свойство для сортировки.const allFrom = tickets.map(item => item.from);
const allTo = tickets.map(item => item.to);
let city = allFrom.filter(item => !allTo.includes(item)).pop(); // первый город
const w = Symbol(); // чтобы случайно не затереть существующее свойство
let i = 0;
let ticket;
while (ticket = tickets.find(t => t.from === city)) {
ticket[w] = i++;
city = ticket.to;
}
// ура! сортировка!
tickets.sort((a, b) => a[w] - b[w]);
tickets.forEach(t => delete t[w]);
function sortTickets(tickets) {
const map = new Map();
const transits = new Set();
tickets.forEach((t) => {
map.set(t.from, t);
transits.add(t.to);
});
const start = tickets.find(t => !transits.has(t.from));
const result = [];
for (let t = start; t; t = map.get(t.to)) {
result.push(t);
}
return result;
}
const sorted = sortTickets([
{from: 'Sochi', to: 'Paris'},
{from: 'Moscow', to: 'Sochi'},
{from: 'London', to: 'Moscow'},
{from: 'Berlin', to: 'Kamchatka'},
{from: 'Paris', to: 'Berlin'},
]);