코딩기록

[89] toggleCompletedById / 객체배열에서 키의 값 중 최대값 구하기, Math.max(...todo.map() => ), 0) 본문

프론트/JS)코딩테스트

[89] toggleCompletedById / 객체배열에서 키의 값 중 최대값 구하기, Math.max(...todo.map() => ), 0)

뽀짝코딩 2024. 8. 8. 21:02
728x90

문제

 

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

 

반응형
Comments