我有一项任务。需要按以下方式对字符串(城市)进行排序:
问题是:我应该使用什么类型的循环以及如何实现排序?我应该使用Array.sort()方法,以及如何动态地将原始城市数组转换为新数组。我应该使用哪种Array.prototype方法?
let cities = [ "New York", "Tokio", "Moscow", "London", "Los Angeles", "Paris", "Berlin", "Madrid", "Kiev", "Oslo", "Barcelona", "Washington", "Ankara", "Rome", "Prague", "Amsterdam", "Minsk"];
function getRandomCity(arr) {
return arr[Math.floor(Math.random()*arr.length)];
}
function sort(arr) {
let unsortedArray = [...arr];
let sortedArray = [];
}
答案 0 :(得分:0)
let cities = ["New York", "Tokio", "Moscow", "London", "Los Angeles", "Paris", "Berlin", "Madrid", "Kiev", "Oslo", "Barcelona", "Washington", "Ankara", "Rome", "Prague", "Amsterdam", "Minsk"];
function getRandomCity(arr) {
return Math.floor(Math.random() * arr.length);
}
function sort(arr) {
let unsortedArray = [...arr];
let sortedArray = [];
let char = "!";
// choose will take an index and then push the city at that index into the sortedArray and remove it from unsortedArray and store the last letter of that city in char (uppercased)
function choose(index) {
let city = unsortedArray.splice(index, 1)[0];
sortedArray.push(city);
char = city.charAt(city.length - 1).toUpperCase();
}
choose(getRandomCity(unsortedArray)); // first of all, choose a random city
while (unsortedArray.length) { // while there still cities
let index, test = unsortedArray.some(function(c, i) { // check if there is a city that begin with char
index = i; // store the index in the process
return c.charAt(0) === char;
});
if(test) // if we found a city
choose(index); // choose it
else // if not
choose(getRandomCity(unsortedArray)); // choose a random one
}
return sortedArray;
}
console.log(sort(cities));

答案 1 :(得分:0)
您可以使用Array.prototype.slice()
,Array.prototype.splice()
,递归从数组中返回随机元素,或者使用首字母,不区分大小写,与上一个元素相同的元素
let cities = [ "New York", "Tokio", "Moscow", "London"
, "Los Angeles", "Paris", "Berlin", "Madrid"
, "Kiev", "Oslo", "Barcelona", "Washington"
, "Ankara", "Rome", "Prague", "Amsterdam", "Minsk"];
let copyCities = cities.slice(0);
function getRandomCity(copy, len, res = []) {
let curr, next;
if (res.length > 0) {
next = copy.filter(function(city) {
var prev = res[res.length -1].slice(-1);
return new RegExp(city[0], "i").test(prev)
});
if (next.length)
next = copy.splice(copy.indexOf(next.shift()), 1);
}
if (copy.length === len || !next.length) {
res.push(copy.splice(Math.floor(Math.random()*copy.length), 1)[0]);
} else {
res.push(next[0]);
}
if (res.length < len) {
return getRandomCity(copy, len, res)
} else {
return res
}
}
var _cities = getRandomCity(copyCities, cities.length);
console.log(_cities);