简体   繁体   中英

How do you get the highest number (value) of it and display the key [name] in ObjectArray of Json using Javascript?

so this is the example I'm trying to work with.

const array = [ { productA: 20 }, {productB: -9}, {productC: 1}, {productD: 6}]

How do you get the highest value but would display the name.

For example the highest here is ProductA that has a value of 20. but upon displaying it should display the key or the ProductA.

It's my first time with these type of problem.

how do you manage to get the highest number, lowest number, and the closest number to 0?

It should always display the key/name.

how do you do this? most of the questions I see here is they have the same key name but different value.

Kindly explain it don't just type the answer.

Array.prototype.sort lets you order arrays:

// sort in descending order
array.sort((a, z) => z - a);

In your case, assuming your objects have always one key only, you need to compare the value instead of the object itself.

const {keys} = Object;
array.sort((a, z) => {
  return z[keys(z)[0]] - a[keys(a)[0]];
});

This will order your array as:

[
  {
    productA: 20
  },
  {
    productD: 6
  },
  {
    productC: 1
  },
  {
    productB: -9
  }
]

Now you have keys(array[0])[0] which is productA , and its value would be 20 .

The last entry will be -9 with key productB .

To find the product closest to 0 you can perform another sort, ignoring one of the entries:

array.sort((a, z) => {
  return 0 - z[keys(z)[0]];
});

This should put the most negative number on top and order positive number so you have your closest to 0 as last entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM