Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 중복된 단어
- 5.3.8 Modifying Queries
- 문자열 중복
- 깃 토큰 만료
- 중복 문자열
- lastIndexOf()
- 중복문자제거
- 프론트엔드 스쿨
- 중첩배열
- 중복단어제거
- indexOf()
- 중첩배열평탄화
- @Moditying @Query
- 스프링 데이타 JPA
- 우분투 시간 변경
- 객체의키값만 찾기
- sql 문자열 패턴 검색
- 코딩 어?
- 시퀄 문법
- 레디스 확인
- 문자열순서바꾸기
- 객체의 밸류값만 찾기
- 제로베이스
- js 문자열을 문자배열로
- 재귀스왑
- 배엘에서 스왑
- ubuntu타임존
- ...점점점문법
- sql like연산자
- 단어 제거
Archives
- Today
- Total
코딩기록
[89] toggleCompletedById / 객체배열에서 키의 값 중 최대값 구하기, Math.max(...todo.map() => ), 0) 본문
프론트/JS)코딩테스트
[89] toggleCompletedById / 객체배열에서 키의 값 중 최대값 구하기, Math.max(...todo.map() => ), 0)
뽀짝코딩 2024. 8. 8. 21:02728x90
문제
todos 배열과 todos 배열의 특정 요소의 id를 인수로 전달하면 해당 요소의 completed 프로퍼티 값을 반전한 todos 배열을 반환한다.
- todos 배열 요소의 id 프로퍼티 값은 절대 중복되지 않는다.
- for 문, for…in 문, for…of 문, Array#forEach, Array#splice는 사용하지 않는다.
- todos 배열을 변경하지 않는다.
const toggleCompletedById = (todos, id) => { /* Do something */ };
const todos = [
{ id: 3, content: 'HTML', completed: false },
{ id: 2, content: 'CSS', completed: true },
{ id: 1, content: 'Javascript', completed: false }
];
console.log(toggleCompletedById(todos, 2));
/*
[
{ id: 3, content: 'HTML', completed: false },
{ id: 2, content: 'CSS', completed: false },
{ id: 1, content: 'Javascript', completed: false }
]
*/
풀이
❗❗배열에서 최대값 찾기 Math.max
1. ( ... ) 스프레드문법-전개연산자
배열에서 Math.max 사용시 ... 스프레드문법-전개연산자 사용해야함.
const arr = [ 1, 2, 3, 7, 100];
console.log( Math.max( ...arr ) ); // 100
2. apply()
apply(첫번째 파라미터, 두번째 파라미터)
apply(Math.max()함수내부에서 사용할 this객체 / 없으면 null, Math.max()함수로 전달할 배열)
const arr = [ 10, 20, 30, 50];
console.log( Math.max.apply(null, arr) ); // 50
1번풀이
1. id만 찾아 내림차순 정렬 [3, 2, 1]
2. 삼항연산자로 인덱스[0]과 최댓값이 같은지 비교, 빈배열일때 0 반환 아니면 최댓값 반환
return orderArr[0] === maxId ? maxId : (arrLength === 0 ? 0 : maxId);
=> 수정
return arrLength === 0 ? 0 : maxId;
인덱스[0]과 최댓값이 같은지 비교 했었는데 그럴필요 없이
첨부터 배열 길이가 0이면 0을 반환, 0이 아니면 최댓값을 반환하면된다.
=> 수정 최대값을 찾을거면 내림차순할 필요가 없음.
=> 최종 코드
빈배열이면 0 이라는 뜻은 값이 최대값 혹은 0 이라는 뜻,
const getMaxId = todos89 => Math.max(...todos89.map((todos89) => todos89.id), 0);
// [89]
//1풀이
const getMaxId = todos89 => Math.max(...todos89.map((todos89) => todos89.id), 0);
//2풀이
const getMaxId = todos => {
const orderArr = todos.map(ids => ids.id);
return orderArr.length === 0 ? 0 : Math.max(...orderArr);
};
//3풀이
const getMaxId = todos => {
const maxId = Math.max(...orderArr);
const arrLength = orderArr.length;
return orderArr[0] === maxId ? maxId : (arrLength === 0 ? 0 : maxId);
};
const todos = [
{ id: 2, content: 'CSS', completed: true },
{ id: 3, content: 'HTML', completed: false },
{ id: 1, content: 'Javascript', completed: false }
];
console.log(getMaxId(todos)); // 3
console.log(getMaxId([])); // 0
2번풀이 - for문
for문 밖에서 빈배열인지 먼저 확인.
빈배열이면 길이가 0 이므로 todos 배열의 길이로 빈배열인지 아닌지 확인한다
// for문 풀이 - id 프로퍼티 값 중에서 최대값 구하기, 빈배열=0
const getMaxId = todos => {
if (todos.length === 0) {
return 0;
}
let result = 0;
for (let i = 0; i < todos.length; i++) {
if (todos[i].id > result) {
result = todos[i].id;
}
}
return result;
};
const todos = [
{ id: 3, content: 'HTML', completed: false },
{ id: 2, content: 'CSS', completed: true },
{ id: 1, content: 'Javascript', completed: false }
];
console.log(getMaxId(todos)); // 3
console.log(getMaxId([])); // 0
참고
*블로그 - 배열에서 최대값 최소값 구하기
https://hianna.tistory.com/487
반응형
'프론트 > JS)코딩테스트' 카테고리의 다른 글
Comments