[英]Natural sort an array of arrays
I need to sort an array of arrays given to me. 我需要对提供给我的数组进行排序。 The array looks something like this. 数组看起来像这样。
var provided_array = [
inner_array_one = ['1', '10', '11', 'Alpha', '2A'],
inner_array_two = ['Hotdogs', 'Pies', 'Burgers', 'Kebabs', 'Tacos']
];
I've kept this example as minimal as possible. 我将这个示例保持在最小限度。 In reality there are usually about a dozen of these inner arrays. 实际上,这些内部数组通常大约有十二个。
The data in inner_array_one is related to that of inner_array_two by index. inner_array_one中的数据通过索引与inner_array_two中的数据相关。 Ie "2A" is related to "Tacos". 即“ 2A”与“炸玉米饼”有关。
The sorting needs to be "natural" ie 2 before 10. The overall expected output I need is 排序必须是“自然的”,即10之前是2。我需要的总体预期输出是
provided_array[
inner_array_one['1', '2A', '10', '11', 'Alpha'],
inner_array_two['Hotdogs', 'Tacos', 'Pies', 'Burgers', 'Kebabs']
];
I've tried to use the javascript sort function but it seems it's only capable of sorting the order of the inner_arrays and not the content of those said arrays. 我尝试使用javascript排序功能,但似乎只能排序inner_arrays的顺序,而不能排序那些表示的数组的内容。
Is what I want achievable? 我想要实现吗?
You could take a helper array for the indices and sort natural the first inner array and map all arrays with the indices array. 您可以为索引使用一个辅助数组,并对第一个内部数组进行自然排序,然后将所有数组与索引数组映射。
var arrays = [ ['1', '10', '11', 'Alpha', '2A'], ['Hotdogs', 'Pies', 'Burgers', 'Kebabs', 'Tacos'] ], indices = Object.keys(arrays[0]); indices.sort((a, b) => arrays[0][a].localeCompare(arrays[0][b], undefined, { numeric: true, sensitivity: 'base' })); console.log(arrays.map(a => indices.map(i => a[i])));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This simple function would sort an array of arrays at any level of nesting: 这个简单的函数可以在任何嵌套级别对数组数组进行排序:
function sortArray(arr) {
if (!Array.isArray(arr) || !arr.length) return;
if (Array.isArray(arr[0]))
arr.forEach(ele => sortArray(ele));
arr = arr.sort();
}
You can use the kn
option of .localeCompare()
for natural sorting of alphanumeric strings. 您可以使用.localeCompare()
的kn
选项对字母数字字符串进行自然排序。
var provided_array = [
inner_array_one = ['1', '10', '11', 'Alpha', '2A'],
inner_array_two = ['Hotdogs', 'Pies', 'Burgers', 'Kebabs', 'Tacos']
];
provided_array.forEach(item => item.sort((obj1, obj2) => obj1.localeCompare(obj2, 'en-US-u-kn-true')));
console.log(provided_array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.