JavaScript - 배열중 최대값 구하기

Moolbum·2021년 11월 12일
0

JavaScript

목록 보기
4/18
post-thumbnail

최대값 구하기 👨‍💻

예시문제는 배열안의 "string" 중에서 가장 긴 값을 구하는 것!

function find_longest_word(arr) {
	
}

let array = ["PHP", "Exercises", "Backend"];
console.log(find_longest_word(array)); 

사용한 메서드

Array 메서드 중 map, Math의 max 메서드를 사용하고indexOf 로 최대값의 배열을 찾았습니다.

map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);

console.log(map1) //[2, 8, 18, 32]

indexOf()

문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, stringName 문자열의 마지막 문자의 순번 stringName.length -1 입니다. indexOf 메서드는 대소문자를 구분합니다.

'Blue Whale'.indexOf('u') // 2;

Math.max()

Math.max()함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.

console.log(Math.max(1, 3, 2)) // 3;

스프레드 연산자 ...

스프레드 연산자를...사용하면 배열, 문자열, 객체 등 반복 가능한 객체를 개별 요소로 분리 할 수 있습니다.

Array
let arr1 = [1, 2, 3, 4, 5]; 
let arr2 = [...arr1, 6, 7, 8, 9]; 

console.log(arr2); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

String
let str1 = 'paper block'; 
let str2 = [...str1]; 
console.log(str2); // [ "p", "a", "p", "e", "r", " ", "b", "l", "o", "c", "k" ]

문제풀이

function find_longest_word(arr) {
  let arrmap = arr.map(x => x.length);
  let maxNumber = Math.max(...arrmap);
  let result = arrmap.indexOf(maxNumber);
  return arr[result];
}
let array = ["PHP", "Exercises", "Backend"];
console.log(find_longest_word(array));

문제풀이는 이렇게 진행되었고 하나하나씩 뜯어서 확인해보면

let arrmap = arr.map(x => x.length);

arrmap을 콘솔 창에 띄우면 [ 3, 9, 6 ] 출력된다.
map메서드로 배열을 반복시켜 arr각 요소의 문자의 length값 출력

arr.map(x =>x.length); 
["PHP", "Exercises", "Backend"] // [ 3, 9, 6 ]

let maxNumber = Math.max(...arrmap);

maxNumber를 콘솔 창에 띄우면 9가 출력된다.
Math.max메서드로 최대값을 출력 합니다. arrmap의 상태는 [3, 9, 6]
이어서 ES6의 문법중 하나인 스프레드 문법 ... 을 이용하여 ...arrmap 배열임을 알립니다. 이제 배열 중의 최대값인 9를 출력합니다.

maxNumber = Math.max(...arrmap) // 9;

스프레드 문법을 쓰지않고 Math.max(arrmap)쓴다면 NaN이 출력됩니다.

let result = arrmap.indexOf(maxNumber);
return arr[result];

arrmap의 배열안의 숫자중[3,9,6] 최댓값의 위치를 가져오는것
출력 되는 숫자는 1 결과 마지막 리턴값은 arr[1] Exercises가 출력된다!

profile
Junior Front-End Developer 👨‍💻

0개의 댓글