JS Algorithm

YJ·2023년 1월 30일
0

문제 1.

const arr = [100, 200, 300]
// code ...

// 결과
[100, 150, 250, 500]

내 코드

const arr = [100, 200, 300];

arr.splice(1, 2, 150, 250, 500);

console.log(arr);

문제 2.

const arr = [1, 3, 4, 6, 9]
// code ...

// 결과
[9, 6, 4, 3, 1]

내 코드

const arr = [1, 3, 4, 6, 9]

let myArr = []
for (let i = arr.length - 1; i >= 0; i--) {
    myArr.push(arr[i]);
}
console.log(myArr)

문제 3. 구구단

for (...) {
    // code ...
}

     
결과
- 다음 단으로 넘어가는 경우 줄바꿈을 해주세요.
- ...은 결과를 한눈에 보기 위해 작성되었습니다.  
- 여러분들은 구구단이 올바르게 출력되도록 코드를 작성해 주세요.

22 * 1 = 2
2 * 2 = 4
...
2 * 9 = 18

33 * 1 = 3
...

99 * 1 = 9
...
9 * 9 = 81

내 코드

for (let j = 2; j < 10; j++) {
  console.log(`${j}`)
  for (let i = 1; i < 10; i++) {
    console.log(`${j} * ${i} = ${j * i}`);
     }
  console.log('\n');
 }

문제 4. 숫자들 중 최댓값 반환

const numbers = "10 11 5 6 12 7 3 9"
// code ...

// 결과
12

내 코드

const numbers = "10 11 5 6 12 7 3 9";

const arr = numbers.split(" ").map(Number);

let first = arr[0];

for (let i = 1; i < arr.length; i++) {
  if (arr[i] > first) {
    first = arr[i];
  }
}
console.log(first);

문제 5. 배열 내 중복 단어 제거

function func(words) {
  // code ...
}

const words = ['Have', 'A', 'Good', 'Time', 'Have', 'Good']
func(words)


// 결과
['Have', 'A', 'Good', 'Time']

내 코드

function func(words) {
  const only = words.filter((element, index) => {      // element => 처리할 현재 요소, index => 처리할 현재 요소의 인덱스 & filter() 메서드는 true 값을 배열로 반환.
    return words.indexOf(element) === index;           // indexOf는 주어진 값과 일치하는 첫 번째 인덱스를 반환. 그러므로 해당 요소의 인덱스와 indexOf가 일치하지 않는다는건 해당 요소가 또 존재한다는 의미!
  })
  return only;
}

<모범답안>
https://wecode.notion.site/JS-Algorithm-b09cd51ce7194650803a20b7ddafbef3

profile
Hello

0개의 댓글