在 JavaScript 中对多维数组进行排序
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有以下数组 −
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","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' ] ]