[SEB_FE_44] JS(6) - 객체 알고리즘

유영준·2023년 2월 28일
post-thumbnail

오늘 배운 주제


  • 객체 알고리즘

오늘 배운 내용


  • for...in문 = 객체 / for...of문 = 배열

  • 새로운 객체

function select(arr, obj) {
  let result = {};
  for(let i of arr) {
    for(let j in obj) {
      if(i === j) { // obj의 키와 arr의 요소가 같으면, 새로운 객체에 담는다
        result[j] = obj[j];
      }
    }
  }
  return result;
}

// const arr = ['a', 'c', 'e'];
// const obj = { a: 1, b: 2, c: 3, d: 4 };

// let output = select(arr, obj);
// console.log(output); // --> { a: 1, c: 3 }
  • 마지막 요소 리턴
function getLastElementOfProperty(obj, property) {
  let newArray = obj[property];
  if (Array.isArray(newArray) && newArray.length !== 0) {
    return newArray[newArray.length - 1];
  } else return undefined;
}

// const obj = {
//  key: [1, 2, 5],
// };

// let output = getLastElementOfProperty(obj, 'key');
// console.log(output); // --> 5
  • 해당 문자가 문자열에서 등장하는 횟수
function countAllCharacters(str) {
  // TODO: 여기에 코드를 작성합니다.
  const letter = str.split('') // ['b', 'a', 'n', 'a', 'n', 'a']

  let count = 0;
  let obj = {};

  if(str.length === 0) return {};

  for (i of letter) {
    for (let j = 0; j < str.length; j++) {
      if(i === str[j]) {
        count++;
      }
      obj[i] = count;
    }
    count = 0;
  }
  return obj;
}

//let output = countAllCharacters('banana');
//console.log(output); // --> {b: 1, a: 3, n: 2}
  • 가장 많이 반복되는 문자
function mostFrequentCharacter(str) {
    // 20번과 유사한 문제
  // 20번 문제는 객체로 만들어서 리턴해주기만 하면 되는데, 이번에는 가장 많이 반복된 문자를 리턴
  // 20번 + '가장 많이 반복' 찾기
  // 가장 큰, 가장 많은 -> 비교 대상 만들어 놓고 하나씩 비교해서 교체하기

  // str이 만약 apple이라면
  // obj = {a: 1, p: 2, l: 1, e: 1} 이렇게 만들어 준다.
  // 가장 많이 나온 문자를 체크할 수 있는 변수를 하나 만들어 놓고,
  // 가장 큰 수를 체크할 수 있는 변수도 하나 만들어 놓고,
  // 그것보다 더 커지면? 교체 -> 가장 큰 수, 가장 많이 나온 문자 둘 다 교체
  let mostChar = '';
  let mostCount = 0;
  let obj = {};
  // 주의 사항 : 띄어쓰기 제외 -> 제외한다는 건 어떻게? continue를 사용하면 된다.
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      continue; 
    }
    if (obj[str[i]] === undefined) {
      obj[str[i]] = 0;
    }
    obj[str[i]]++

    if (obj[str[i]] > mostCount) {
    // 반복문을 돌다가 어느 순간 문자열에 해당하는 값이 mostCount보다 커지면? mostCount와 mostChar교체
    // {a: 1} -> 교체 -> mostCount:1, mostChar: 'a'
    // {a: 1, p: 2} -> 교체 -> mostCount:2, mostChar: 'p'
    // (반복...)
    // {a: 1, p: 2, l: 1, e: 1}
      mostCount = obj[str[i]];
      mostChar = str[i];
    }
  }
  // 마지막엔 가장 많이 나온 문자 리턴
  // 'p'
  return mostChar;
}

// let output = mostFrequentCharacter('apples not oranges');
// console.log(output); // --> 'p'

// output = mostFrequentCharacter('hello world');
// console.log(output); // --> 'l'

// output = mostFrequentCharacter('   ');
// console.log(output); // --> ''

// output = mostFrequentCharacter('');
// console.log(output); // --> ''

// output = mostFrequentCharacter('abba');
// console.log(output); // --> 'b'

오늘의 과제


  • 객체

가장 많이 반복되는 문자 문제 복습 필수

그동안 코딩테스트를 배열로 된 문제만 풀어서 객체로된 문제를 처음 경험했는데 내가 객체를 잘못 이해한건지 초반 문제부터 헤매기 시작.

다행히 레퍼런스가 있어서 못 푼 문제는 없었는데 문제 유형이 생소해서 아직 완전히 이해는 못함.

profile
프론트엔드 개발자 준비 중

0개의 댓글