<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>字符串排序</title>
</head>
<body>
<script>
// 排序 升序
var string =
"10楼1号主机 1楼10号主机 1楼1号主机 11楼2号主机 9楼2号主机 8楼1号主机";
var myArray = string.split(" ");
// => ["10楼1号主机", "1楼10号主机", "1楼1号主机", "", "11楼2号主机", "9楼2号主机", "8楼1号主机"]
var reg = /\d{1,}/g;
myArray = myArray.map(item => {
return item.match(reg);
});
var array = myArray;
// 排序 => 升序 第一个数字表示第几层楼 第二个数字表示第几台空调
function defaultCompare(a, b, c, d) {
return a > c ? true : a == c ? (b > d ? true : false) : false;
}
function swap(array, a, b) {
[array[a], array[b]] = [array[b], array[a]];
}
function bubbleSort(array, compareFn = defaultCompare) {
const { length } = array;
for (let i = 0; i < length - 1; i++) {
for (let j = 0; j < length - 1 - i; j++) {
let [a, b] = array[j];
let [c, d] = array[j + 1];
if (compareFn(parseInt(a), parseInt(b), parseInt(c), parseInt(d))) {
swap(array, j, j + 1);
}
}
}
return array;
}
bubbleSort(array);
console.log(array); // => [["1", "1"], ["1", "10"], ["8", "1"], ["9", "2"], ["10", "1"], ["11", "2"]]
var newArr = [];
array.map(val => {
string.split(" ").map(item => {
let [m, n] = item.match(reg);
let [p, q] = val;
if (m == p && n == q) {
newArr.push(item);
}
});
});
console.log(newArr); // => ["1楼1号主机", "1楼10号主机", "8楼1号主机", "9楼2号主机", "10楼1号主机", "11楼2号主机"]
</script>
</body>
</html>
网友评论