Home > Net >  Determin Highest Value on Array of Objects [duplicate]
Determin Highest Value on Array of Objects [duplicate]

Time:09-17

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.

CodePudding user response:

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]);

  • Related