[英]How can I sort the index of a nested array according to a specific key?
I have a nested array that consists of the following strucure:我有一个嵌套数组,包含以下结构:
arr: Array(2)
0: [id: 1, area: 111, area_str: "111,00 m²"]
1: [id: 2, area: 555, area_str: "555,00 m²"]
I am trying to sort whole nested arrays based on a given key and its corresponding value.我正在尝试根据给定的键及其对应的值对整个嵌套的 arrays 进行排序。 So for example when the key provided is "area" then the nested items with the index 0 and 1 should be reordered as a whole according to the sorting result that is calculated by comparing the values of the given key.
因此,例如,当提供的键是“区域”时,索引为 0 和 1 的嵌套项应根据通过比较给定键的值计算的排序结果作为一个整体重新排序。
Referring to this example the desired output should look like this:参考此示例,所需的 output 应如下所示:
arr: Array(2)
0: [id: 2, area: 555, area_str: "555,00 m²"]
1: [id: 1, area: 111, area_str: "111,00 m²"]
The sorting mechanism should work both in ascending and descending order.排序机制应该按升序和降序工作。 I already tried to make use of the sort() function but I only found examples for sorting the keys or values within ONE array and not for sorting nested sub-arrays by changing their index position.
我已经尝试使用 sort() function 但我只找到了对 ONE 数组中的键或值进行排序的示例,而不是通过更改索引 position 对嵌套子数组进行排序的示例。
I would be glad if you could give me some advice about how this could be achieved.如果你能给我一些关于如何实现这一点的建议,我会很高兴。 Thanks in advance!
提前致谢!
Here a small example how to sort an array of objects:这是一个如何对对象数组进行排序的小示例:
let array = [ {id: 1, area: 555, area_str: "111,00 m²"}, {id: 2, area: 111, area_str: "555,00 m²"}, {id: 3, area: 333, area_str: "333,00 m²"} ] function sortArray(array, property, isDescending) { if(isDescending) { array.sort((a,b) => (a[property] > b[property]? -1: 1 )); } else { array.sort((a,b) => (a[property] > b[property]? 1: -1 )); } } sortArray(array, 'id', true); console.log(array); sortArray(array, 'area', false); console.log(array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.