본문 바로가기
기초다지기/JS 코딩테스트

Lv0 배열의 원소만큼 추가하기

by 김빵그 2023. 5. 21.

  • 보자마자 이거,, lv0이 맞나 ..의심했던 문제.. ! 생각보다 머리를 많이 쓰게 했다 repeat이 먼저 생각나긴 했지만 저건 array고.. 또 뭐를 써야하는지 공식 문서를 뒤져보며 여러 구글링을 통해 답을 이렇게 내버림.. (옛날 코드 느낌) 

내답

function solution(arr) {
    var answer = [];
    return  Array.from(arr, x => Array(x).fill(x)).flat();
}

1. Array.from()

console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// Expected output: Array [2, 4, 6]


Array.from(arrayLike[, mapFn[, thisArg]])
  • Array.from() 메서드는 유사배열 객체나 반복 가능한 객체를 얕게 복사해 새로운 arr 객체를 만든다
  • arrayLike : 배열로 변환하고자 하는 유사 배열 객체나 반복 가능한 객체
  • mapFn : 배열의 모든요소에 대해 호출할 맵핑 함수
  • thisArg : mapFn 실행 시에 this로 사용할 값

2. Array.prototype.fill()

const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]


 arr.fill(value[, start[, end]])
  • fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채움
  • value : 배열을 채울 값
  • start : 시작 인덱스, 기본값은 0
  • end : 끝 인덱스, 기본값은 this.length

3. Array.prototype.flat()

const newArr = arr.flat([depth])
  • 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성
  • depth : 중첩 배열 구조를 평탄화 할 때 사용할 깊이 의 값 기본값은 1.

 

다른 답들

function solution(arr) {
    var answer = [];
    for(let i = 0; i<arr.length; i++){
        for(let j = 0; j<arr[i]; j++){
            answer.push(arr[i]);
        }
    }
    return answer;
}
function solution(arr) {
  let ans = [];

  arr.forEach((value) => {
    for (let i = 0; i < value; i++) {
      ans.push(value);
    }
  });

  return ans;
}
function solution(arr) {
    return arr.map(a=>Array(a).fill(a)).flat();
}