2

I try to define the rank cars from most expensive to least expensive, using javascript, but I don’t know how to make it the rank.

For now, I am still using the data object array.

<script>
var cars = [];
cars.push({"mobil" : "Kijang Inova", "price" : 300});
cars.push({"mobil" : "Nissan", "price" : 180});
cars.push({"mobil" : "Expander", "price" : 200});

console.log(cars);
</script>


So I Hope get output like this:

[{mobil : "Kijang Inova", "price" : 300, rank : 1},
{mobil : "Expander, "price" :200, rank : 2},
{mobil : "Nissan, "price" : 180, rank : 3}]
Lloyd Nicholson
  • 474
  • 3
  • 12
kayum iman
  • 39
  • 1
  • 4
  • 1
    Possible duplicate of [Sorting arrays in javascript by object key value](https://stackoverflow.com/questions/7889006/sorting-arrays-in-javascript-by-object-key-value) – Dmitry Jan 01 '19 at 07:08

1 Answers1

1

You could do this

var cars = [];
cars.push({"mobil" : "Kijang Inova", "price" : 300});
cars.push({"mobil" : "Nissan", "price" : 180});
cars.push({"mobil" : "Expander", "price" : 200});

let rank = 1;

cars.sort((a,b) => {
  return b['price'] - a['price']
});
cars.forEach(car => {
  car.rank = rank;
  rank ++;
});
console.log(cars);
ibn_Abubakre
  • 112
  • 7