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:
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
CodePudding user response:
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.