Please help on this how to achieve on JavaScript. I have data type . The aim of this sorting is I have object columns where columns are not arranged as it required. This function below simply arrange array column for example. I have tested this code in my local machine and this is the output that I have got.
<?php
$data = '[
{
"from": "Barcelona",
"to": "New York",
"instruction": "",
"time": "2018-02-02 20:05",
"transport": "Flight",
"transportno": "B33",
"seatno": "Y15"
},
{
"from": "Barcelona",
"to": "Gerona",
"instruction": "",
"time": "2018-02-02 20:05",
"transport": "Bus",
"transportno": "M31, M32, M33",
"seatno": "Any"
},
{
"from": "Madrid",
"to": "Barcelona",
"instruction": "",
"time": "2018-02-02 20:05",
"transport": "Bus",
"transportno": "M31, M32, M33",
"seatno": "Any"
},
{
"from": "New York",
"to": "Stockholm",
"instruction": "",
"time": "2018-02-02 20:05",
"transport": "Flight",
"transportno": "M31, M32, M33",
"seatno": "Any"
},
{
"from": "Gerona",
"to": "Barcelona",
"instruction": "",
"time": "2018-02-02 20:05",
"transport": "Bus",
"transportno": "M31, M32, M33",
"seatno": "Any"
}
]';
Now I need the data sorted in this way flight from Madrid to Barcelona then Barcelona to Gerona - Gerona to Barcelona - Barcelona to New York - New York to Stockholm -
$data_decode = json_decode($data, true);
usort($data_decode, function ($a, $b) {
return $a['to'] === $b['from'] ? 0 : 1;
});
print_r($data_decode);
Output
Array ( [0] => Array ( [from] => Madrid [to] => Barcelona [instruction] => [time] => 2018-02-02 20:05 [transport] => Bus [transportno] => M31, M32, M33 [seatno] => Any )
[1] => Array
(
[from] => Barcelona
[to] => Gerona
[instruction] =>
[time] => 2018-02-02 20:05
[transport] => Bus
[transportno] => M31, M32, M33
[seatno] => Any
)
[2] => Array
(
[from] => Gerona
[to] => Barcelona
[instruction] =>
[time] => 2018-02-02 20:05
[transport] => Bus
[transportno] => M31, M32, M33
[seatno] => Any
)
[3] => Array
(
[from] => Barcelona
[to] => New York
[instruction] =>
[time] => 2018-02-02 20:05
[transport] => Flight
[transportno] => B33
[seatno] => Y15
)
[4] => Array
(
[from] => New York
[to] => Stockholm
[instruction] =>
[time] => 2018-02-02 20:05
[transport] => Flight
[transportno] => M31, M32, M33
[seatno] => Any
)
) [Finished in 0.1s]
How I can get this result in JavaScript. You help will be appreciated.