Problem
I have a 2d-array, which is actually data entered into Google Sheet. It is sorted by logic, defined by a user.
The goal is to enter new lines at the end of this table and then sort it by position.
Saying "by position" I mean "Europe" goes before "America" because a user has entered it earlier.
Here is sample array for tests:
var data =
[
['Earth', 'Europe', 'Britain', 'London'],
['Earth', 'Europe', 'Britain', 'Manchester'],
['Earth', 'Europe', 'Britain', 'Liverpool'],
['Earth', 'Europe', 'France', 'Paris'],
['Earth', 'Europe', 'France', 'Lion'],
['Earth', 'Europe', 'Italy', 'Rome'],
['Earth', 'Europe', 'Italy', 'Milan'],
['Earth', 'Europe', 'Greece', 'Athenes'],
['Earth', 'Asia', 'China', 'Pekin'],
['Earth', 'Africa', 'Algeria', 'Algiers'],
['Earth', 'America', 'USA', 'Dallas'],
['Earth', 'America', 'USA', 'New York'],
['Earth', 'America', 'USA', 'Chicago'],
['Tatooine', 'Yulab', 'Putesh', 'ASU'],
['Tatooine', 'Yulab', 'Putesh', 'Niatirb'],
['Tatooine', 'Yulab', 'Zalip', 'Duantan'],
['Tatooine', 'Asia', 'Solo', 'Lion'],
['Tatooine', 'Asia', 'Solo', 'To'],
['Earth', 'America', 'USA', 'San Francisco'],
['Tatooine', 'Yulab', 'Koko', 'Traiwau'],
['Venus', 'Yoo', 'Van', 'Derzar'],
['Tatooine', 'Chendoo', 'org', 'Eccel']
];
And correct resulting array is:
/*
[ [Earth, Europe, Britain, London],
[Earth, Europe, Britain, Manchester],
[Earth, Europe, Britain, Liverpool],
[Earth, Europe, France, Paris],
[Earth, Europe, France, Lion],
[Earth, Europe, Italy, Rome],
[Earth, Europe, Italy, Milan],
[Earth, Europe, Greece, Athenes],
[Earth, Asia, China, Pekin],
[Earth, Africa, Algeria, Algiers],
[Earth, America, USA, Dallas],
[Earth, America, USA, New York],
[Earth, America, USA, Chicago],
[Earth, America, USA, San Francisco],
[Tatooine, Yulab, Putesh, ASU],
[Tatooine, Yulab, Putesh, Niatirb],
[Tatooine, Yulab, Zalip, Duantan],
[Tatooine, Yulab, Koko, Traiwau],
[Tatooine, Asia, Solo, Lion],
[Tatooine, Asia, Solo, To],
[Tatooine, Chendoo, org, Eccel],
[Venus, Yoo, Van, Derzar]
]
*/
I want to use a script for this.
My Solution
I've made my own version of a script, please see here:
https://github.com/Max-Makhrov/positional-sorting/blob/master/main.js
How the algorithm works
The algorithm finds groups starting from the first row: Earth > Europe > Britain. Then it tries to find a match for this groups in later entries.
I also thought about assigning higher indexes to earlier entries.
Question
The question: are there better approaches:
- less code to accomplish the same task
- More general ways to sort an array by position
- Need fast enough solution, because I will use the code in sheets and it has limits on script time.