[英]Javascript: reorder a large multidimensional array based on another array
I have a multidimensional array that behaves like a spreadsheet. 我有一个行为类似于电子表格的多维数组。 First item it's a column header: 第一项是列标题:
[
['A', 'B', 'C', 'D'],
[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[...]
]
Order of the "columns" is defined by another array: “列”的顺序由另一个数组定义:
['C', 'A', 'D', 'B']
Expected result is: 预期结果是:
[
['C', 'A', 'D', 'B'],
[ 3 , 1 , 4 , 2 ],
[ 7 , 5 , 8 , 6 ],
[...]
]
Would .map
, .splice
and .indexOf
be the best approach? .map
, .splice
和.indexOf
是最好的方法吗? What about their performance on a 20k+ array? 他们在20k +阵列上的性能如何?
Thanks! 谢谢!
function reorder(data, order) { let header = data[0]; let orderIndex = order.map(i => header.indexOf(i)); return data.map(row => orderIndex.map(i => row[i])); } let data = [ ['A', 'B', 'C', 'D'], [ 1 , 2 , 3 , 4 ], [ 5 , 6 , 7 , 8 ], ]; let order = ['C', 'A', 'D', 'B']; console.log(reorder(data, order));
As for performance... you'll need to test it. 至于性能...您需要对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.