First you need to extract the amounts from the Object that has the items. See that it is an array (items: [ ... ]), so you can interact with the elements using for or foreach, but it is simpler using array functions in javascript, as map, that interacts over each element of an array, and we can resume only the amount that is what matters, and then order using sort, which is another method of an array, see the example:
var lista = {
"items": [{
"description": "Smartphone Motorola",
"id": "123",
"quantity": 5
},
{
"description": "Smartphone Samsung",
"id": "456",
"quantity": 3
},
{
"description": "Smartphone Samsung",
"id": "678",
"quantity": 7
}
]
};
let qtde = lista.items
.map(item => item.quantity);
qtde.sort();
console.log(qtde);
Note that in this case the order was ascending. To make a descending order, we must pass to the method sort one Function whether you will receive two values. This Function must return a value less than zero if the first value is greater, zero if they are equal and a value greater than zero if the second is greater.
So we can simply subtract the second from the first, as we want to order downwards:
var lista = {
"items": [{
"description": "Smartphone Motorola",
"id": "123",
"quantity": 5
},
{
"description": "Smartphone Samsung",
"id": "456",
"quantity": 3
},
{
"description": "Smartphone Samsung",
"id": "678",
"quantity": 7
}
]
};
let qtde = lista.items
.map(item => item.quantity);
qtde.sort(function(n1, n2) {
return n2 - n1;
});
console.log(qtde);
Now just take this list and add each value to an element UL. We could do this with functions like join, but to make it simpler to understand, I will use the foreach:
var lista = {
"items": [{
"description": "Smartphone Motorola",
"id": "123",
"quantity": 5
},
{
"description": "Smartphone Samsung",
"id": "456",
"quantity": 3
},
{
"description": "Smartphone Samsung",
"id": "678",
"quantity": 7
}
]
};
let qtde = lista.items
.map(item => item.quantity);
qtde.sort(function(n1, n2) {
return n2 - n1;
});
// variável que tem a lista UL
let ul = document.getElementById("lista");
for (var i = 0; i < qtde.length; i++) {
// criar um elemento LI
var li = document.createElement('li');
// adicionar o valor no LI
li.appendChild(document.createTextNode(qtde[i]));
// adicionar o LI na lista UL
ul.appendChild(li);
}
<p>Smartphone Motorola</p>
<ul id="lista" class="dropdown-menu"></ul>
There are other ways to do this, but it is demonstrated how to extract the values, sort and add to the list, in different parts.