1

if I have something like this:

var lowestPricesCars =
{
  HondaC:
  {
    owner: "",
    price: 45156
  },
  FordNew:
  {
    owner: "",
    price:4100
  },
  HondaOld:
  {
    owner: "",
    price: 45745
  },
  FordOld:
  {
    owner: "",
    price: 34156
  },
}

How can I order the cars based on price ?

Please if the question is not clear then comment it out.

Thanks

3
  • lowestPricesCars is an object with cars sorted by the order that they are inserted into lowestPricesCars. Consistent, value based sorting is best done via arrays rather than objects - would you like to see an example of this? Commented Nov 18, 2018 at 19:08
  • @DacreDenny thanks for the suggestion. But I have built my code already using an object. Changing it to an array will be too much work. Is there a quick way to change it to array and order it and then return back to object ? Commented Nov 18, 2018 at 19:12
  • 2
    " to array then back to object" . Still not reliable with regard to order. Will need to change your code instead. Commented Nov 18, 2018 at 19:16

2 Answers 2

1
const arrayOfKeys = Object.keys(lowestPricesCars)
const keysSortedByPrice = arrayOfKeys.sort((a,b) => {
  return lowestPricesCars[a].price - lowestPricesCars[b].price;
});
let carsSortedByPrice = {}
keysSortedByPrice.forEach(key => carsSortedByPrice[key] = lowestPricesCars[key])

If you want to reverse the order:

return lowestPricesCars[b].price - lowestPricesCars[a].price;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! Works like a charm :D
0

You can do this in a concise way via ES6 Object.entries, Array.sort and Array.reduce.

However object's key order is not guaranteed and not consistent between browsers and it is not recommended to be used.

const data = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", price: 34156 } }

console.log(Object.entries(data)
  .sort((a,b) => a[1].price - b[1].price)  // for DESC b[1].price - a[1].price
  .reduce((r,[k,v]) => (r[k] = v, r), {}))

Comments

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.