0

I have this problem where the array of objects is intendedly put into this kind of structure:

const productArray = [ { 'Product A': 5000 }, { 'Product B': 2500 }, { 'Product C': 3500 }, { 'Product D': 2750 }, { 'Product E': 1500 }, ]; 

On what way could I determine the highest and lowest value of this kind of array? Thank you very much.

2
  • 1
    You're probably better off using a different structure. Either use a single object with different properties, or use an array with the values. Or alternatively an array of objects with both the product name and its value as separate properties. Having an array of objects where every object has a different property is making your own live needlessly hard. Commented Sep 13, 2021 at 7:37
  • @ivar I wish it was the case. But the problem was intendedly put it in this structure. Commented Sep 13, 2021 at 7:45

1 Answer 1

1

Sort the array, Lowest one will be at first and Largest one will be at last

const productArray = [ { 'Product A': 5000 }, { 'Product B': 2500 }, { 'Product C': 3500 }, { 'Product D': 2750 }, { 'Product E': 1500 }, ]; const sortedProduct = productArray.sort((a, b) => Object.values(a)[0] - Object.values(b)[0]); console.log(sortedProduct); console.log('Lowest value ', sortedProduct[0]); console.log('Highest value ', sortedProduct[sortedProduct.length - 1]);

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

9 Comments

Thank you so much @andy. I'll try to understand this as this gave a better outcome for my other key:value pair.
No problem. I've updated the fiddle with some comments about how it works, and some links to the relevant documentation. @Shironekomaru
Thanks! There's probably a clever one-liner in there somewhere but I hope the steps I outlined made it easier to understand. @Shironekomaru.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.