Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the largest numbers in an unordered array

I need to find the largest number in an unordered array (javascript)

[[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]]

This should be the result -> [-34, -2, 7]

I have tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let brojevi = [
  [-34, -54, -74],
  [-32, -2, -65],
  [-54, 7, -43]
];

let pronadjiNajveciBroj = (brojevi) => {
  let najveci = brojevi[0];
  for (let i = 0; i < brojevi.length; i++) {
    if (brojevi[i] > najveci) {
      najveci = brojevi[i];
    } else {
      console.log("Ovo nije najveci broj")
    }
  };

  return {
    najveci
  };
};
console.log(pronadjiNajveciBroj(brojevi));

but I only get the last array as a result

>Solution :

const a = [[-34, -54, -74], [-32, -2, -65], [-54, 7, -43]];
const r = a.map(e=>Math.max(...e));
console.log(r);

a.map() takes an array and returns another array formed by transforming each element (an array in this case) with a function.

Math.max() takes a list of comma-separated values and returns the maximum value.

The spread operator … yields a list of comma-separated values from an array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading