简体   繁体   中英

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. 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.

Referring to this example the desired output should look like this:

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM