在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' ] ]