This question has already been answered:

Suppose there is a multidimensional json-array consisting of similar elements:

{ "manufacturer": "Apple", "name": "iPhone", "model": "7 Plus", "memory": [ "32GB", "128GB", "256GB" ], "colours": [ "Gold", "Silver", "Pink", "Black" ], "terms": [ { "instalment_full_price": "49$/month", "instalment_price": 49, "price": 799 } ] } 

How can these elements be sorted among themselves in ascending price by the value of the key terms[0].price ?

Reported as a duplicate by participants Alexey Shimansky , Nick Volynkin 26 Aug '17 at 6:55 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • that's interesting. You asked this question on July 31. Sort json-arrays by value inside , you were given a link to a duplicate. Is it really so difficult to read and apply? or the brain does not work at all? - Alexey Shimansky

1 answer 1

The sort function takes as its argument a function, which in turn receives 2 elements. They need to be compared and returned -1, 0 or 1. More on MDN .

 const arr = [ { "manufacturer": "Apple", "name": "iPhone", "model": "7 Plus", "memory": [ "32GB", "128GB", "256GB" ], "colours": [ "Gold", "Silver", "Pink", "Black" ], "terms": [ { "instalment_full_price": "49$/month", "instalment_price": 49, "price": 7992 } ] }, { "manufacturer": "Apple", "name": "iPhone", "model": "7 Plus", "memory": [ "32GB", "128GB", "256GB" ], "colours": [ "Gold", "Silver", "Pink", "Black" ], "terms": [ { "instalment_full_price": "49$/month", "instalment_price": 49, "price": 7991 } ] }, { "manufacturer": "Apple", "name": "iPhone", "model": "7 Plus", "memory": [ "32GB", "128GB", "256GB" ], "colours": [ "Gold", "Silver", "Pink", "Black" ], "terms": [ { "instalment_full_price": "49$/month", "instalment_price": 49, "price": 79956 } ] }, { "manufacturer": "Apple", "name": "iPhone", "model": "7 Plus", "memory": [ "32GB", "128GB", "256GB" ], "colours": [ "Gold", "Silver", "Pink", "Black" ], "terms": [ { "instalment_full_price": "49$/month", "instalment_price": 49, "price": 7995 } ] } ] const newArr = arr.sort((a,b) => a.terms[0].price > b.terms[0].price) console.log(newArr) 

  • boolean? (2 characters needed ...) - Igor
  • Thanks for the code. Strange, but in my case the comparison a > b did not work, and the comparison a - b worked. - JamesJGoodwin