๋ฐ์ํ
1. reduce ์ฌ์ฉํ๊ธฐ
// For large data, it's better to use reduce. Supose arr has a large data in this case:
const arr = [1, 5, 3, 5, 2];
const max = arr.reduce((a, b) => { return Math.max(a, b) });
// console.log(max);
// 5
2. Math.max.apply ์ฌ์ฉํ๊ธฐ
// For arrays with relatively few elements you can use apply:
const arr = [1, 5, 3, 5, 2];
const max = Math.max.apply(null, arr);
//console.log(max);
//5
3. spread syntax ์ฌ์ฉํ๊ธฐ
// or spread operator:
const arr = [1, 5, 3, 5, 2];
const max = Math.max(...arr);
//console.log(max)
//5
๋ฒ์ธ 1. ์๋ฐ์คํฌ๋ฆฝํธ, ๋ฌธ์์ด ๋ฐฐ์ด์์ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๊ธด ๋ฌธ์์ด์ ๋ฆฌํด
function getLongestElement(arr) {
// ๋ฐฐ์ด ์์ ์์์ ๊ธธ์ด๋ฅผ ์์์ผํ๋ค.
// ๊ทธ๋ฆฌ๊ณ ์ต์ข
๋ฆฌํด ๊ฐ์ ๋ฐฐ์ด์ ์์๊ฐ
return arr.reduce((acc, cur) => {
if(acc.length < cur.length){
return cur;
} else {
return acc;
}
},'')
}
๋ฒ์ธ 2. ์๋ฐ์คํฌ๋ฆฝํธ, ๋ฌธ์์ด ๋ฐฐ์ด์์ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๊ธด ๋ฌธ์์ด์ ๊ธธ์ด๋ฅผ ๋ฆฌํด
๋ฐฉ๋ฒ1
function getLengthOfLongestElement(arr) {
let mapped = arr.map(e => e.length);
if(arr.length === 0) {
return 0;
}
return Math.max.apply(null,mapped);
}
๋ฐฉ๋ฒ2
function getLengthOfLongestElement(arr) {
if(arr.length === 0) {
return 0;
}
return arr.reduce((acc, cur) => {
if(acc.length >= cur.length) {
return acc;
} else {
return cur;
}
},0).length;
}
๋ฐ์ํ