JavaScript/메소드

[javascript] 전개연산자, 정규식, reduce 연습

Angry Stock 2023. 9. 14. 12:08
반응형
전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// Expected output: 6

console.log(sum.apply(null, numbers));
// Expected output: 6
[^0-9] : 0부터 9까지 포함하지 않음
reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue);

console.log(sumWithInitial);
// Expected output: 10
연습
function solution1(a) {
  let sum = 0;
  for (let i = 0; i < a.length; i++) {
    if (a[i] < 10) {
      sum += Number(a[i]);
    }
  }
  return sum;
}

function solution2(a) {
  let sum = 0;
  [...a].map((e) => {
    if (Number(e)) sum += Number(e);
  });
  return sum;
}

function solution3(a) {
  return a
    .replace(/[^0-9]/g, '')
    .split('')
    .reduce((acc, curr) => acc + Number(curr), 0);
}

let a = ['e1n4t5r6o7p8hy', 'b34ase6m7e8nt', 'ove9r6w3ehw2e2lm', 'k2ic36557k'];

for (let i = 0; i < a.length; i++) {
  console.log('solution1', solution1(a[i]));
  console.log('solution2', solution2(a[i]));
  console.log('solution3', solution3(a[i]));
}
결과

반응형