0

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!

1
  • This does not look like nested Arrays, but rather an Array of Objects (hint: area is not a valid numeric index for an Array) Commented Oct 25, 2019 at 23:06

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your advice. The creation of my array was falsy which prevented the sort method from executing properly. I added the index level manually by creating empty objects with the respective index and afterwards adding the data into these objects instead of using the native push method to add another object representing another table row to the array. After changing the structure of the given array, your proposed solution works flawlessly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.