# 盛大无线面试题
题目(盛大无线面试题):在一个字符串数组中有红、黄、蓝三种颜色的球,且个数不相等、顺序不一致,请为该数组排序。 使得排序后数组中球的顺序为:黄、红、蓝。 例如:红蓝蓝黄红黄蓝红红黄红,排序后为:黄黄黄红红红红红蓝蓝蓝。
const ball = ['红', '蓝', '蓝', '黄', '红', '黄', '蓝', '红', '红', '黄', '红'];
function ballSort(ball, rule) {
if (!ball.length) return [];
if (!rule || !rule.length) return ball;
let group = {};
for (let i = 0; i < ball.length; i++) {
// eslint-disable-next-line no-prototype-builtins
if (group.hasOwnProperty(ball[i])) {
group[ball[i]].push(ball[i]);
} else {
group[ball[i]] = [ball[i]];
}
}
let newBall = [];
for (let ii = 0; ii < rule.length; ii++) {
newBall = newBall.concat(group[rule[ii]]);
}
group = null;
return newBall;
}
console.time('ballSort');
console.log(ballSort(ball, ['黄', '红', '蓝']));
console.timeEnd('ballSort');