[알고리즘] Q1-5 (splice, unshift, for loop, parseInt, Math.max, indexOf, filter)

JY·2023년 4월 21일

CodeKata

목록 보기
3/5
  1. Array.prototype.splice()

    MDN Syntax
    splice(start)
    splice(start, deleteCount)
    splice(start, deleteCount, item1)
    splice(start, deleteCount, item1, item2, itemN)

// 문제 1

const arr = [100, 200, 300]

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

console.log(arr); // 결과값: [100, 150, 250, 500]
  1. Array.prototype.unshift()

    MDN
    The unshift() method adds the specified elements to the beginning of an array and returns the new length of the array.

// 문제 2 

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

for (let i=0; i<arr.length; i++) {
  result.unshift(arr[i]);
}

console.log(result); // 결과값 [9, 6, 4, 3, 1]
  1. 구구단 프로그램 출력
// 문제 3

for (let i=2; i<10; i++) {
    console.log(`${i}`)

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

    console.log(``) //구구단 프로그램 출력
}
  1. 공백으로 구분된 8개의 숫자들 중 최댓값을 반환하는 코드
    parseInt() : string을 number형으로 변환
// 문제 4

const numbers = "10 11 5 6 12 7 3 9"
let arr = numbers.split(" ").map((num)=> parseInt(num))
console.log(Math.max(...arr)); // 결과값 12
  1. 배열 내 중복된 단어를 제거하는 함수
    Array.prototype.indexOf()

    MDN
    The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
    MDN Syntax
    indexOf(searchElement)
    indexOf(searchElement, fromIndex)

// 문제 5
function func(words){
 const result = words.filter ((word, index)=>{
 return words.indexOf(word)===index
}) 
console.log(result); 
}

const words = ['Have', 'A', 'Good', 'Time', 'Have', 'Good']
func(words) // 결과값 ['Have', 'A', 'Good', 'Time']

출처
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

profile
Hello World!

0개의 댓글