对 JavaScript 中的多维数组进行排序
假设,我们有以下数组 −
const arr = [ ["A","F","A","H","F","F"], ["F","A","A","F","F","H"] ];
我们需要写一个 JavaScript 函数,输入一个这样的数组。
该函数应根据以下规则对给定数组的所有子数组进行内部排序 −
- 如果元素不是“A”或“F”,它们应保持其位置
- 如果元素为“A”或“F”,它们应按字母顺序排序
因此,以上数组的最终输出应如下所示 −
const output = [ ["A","A","A","H","A","F"], ["F","F","F","F","F","H"] ];
请注意,如果排序算法这样做,则来自子数组的元素可以更改其数组。
示例
const arr = [
["A","F","A","H","F","F"],
["F","A","A","F","F","H"]
];
const customSort = (arr = []) => {
const order = [].concat(...arr.slice()),
res = []; order.forEach((el, ind) => {
if (el === 'A') {
const fIndex = order.indexOf('F');
if (fIndex < ind){
order[fIndex] = 'A'; order[ind] = 'F';
};
};
})
arr.forEach(el => res.push(order.splice(0, el.length)))
return res;
}
console.log(customSort(arr));输出
控制台中的输出将是 −
[ [ 'A', 'A', 'A', 'H', 'A', 'F' ], [ 'F', 'F', 'F', 'F', 'F', 'H' ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP