removeSmallest.js (7kyu 30)

Codewars 알고리즘 풀이


Problem

  • Given an array of integers, remove the smallest value.
    • 주어진 정수 배열에서, 가장 작은 값을 제거한다.
  • Do not mutate the original array.
    • 기존 배열을 변경하지 않는다.
  • If there are multiple elements with the same value, remove the one with a lower index.
    • 동일한 값의 여러 element가 있는 경우, index가 낮은 값을 제거한다.


Solution 01

function removeSmallest(arr) {
  const indexOfSmallest = arr.indexOf(Math.min(...arr));
  return arr.slice(0, indexOfSmallest).concat(arr.slice(indexOfSmallest + 1));
}

removeSmallest([1, 2, 3, 4]);  // [2, 3, 4]
removeSmallest([1, 1, 2, 3]);  // [1, 2, 3]
removeSmallest([4, 1, 1, 4]);  // [4, 1, 4]

indexOf(): 주어진 값이 처음으로 나타나는 위치를 반환한다. 일치하는 값이 없으면 -1을 반환한다.

Math.min(): 값이 가장 작은 수를 반환한다.

concat(): 두 개 이상의 배열을 결합하고, 새 배열을 반환한다.

slice(): 문자열/배열의 일부를 추출하고, 새 문자열/배열로 반환한다.


Solution 02

function removeSmallest(arr) {
  const indexOfSmallest = arr.indexOf(Math.min(...arr));
  return [...arr.slice(0, indexOfSmallest), ...arr.slice(indexOfSmallest + 1)];
}

removeSmallest([1, 2, 3, 4]);  // [2, 3, 4]
removeSmallest([1, 1, 2, 3]);  // [1, 2, 3]
removeSmallest([4, 1, 1, 4]);  // [4, 1, 4]


Solution 03

function removeSmallest(arr) {
  const indexOfSmallest = arr.indexOf(Math.min(...arr));
  return arr.filter((i, index) => index !== indexOfSmallest);
}

removeSmallest([1, 2, 3, 4]);  // [2, 3, 4]
removeSmallest([1, 1, 2, 3]);  // [1, 2, 3]
removeSmallest([4, 1, 1, 4]);  // [4, 1, 4]

filter(): 테스트를 통과한 배열의 각 값을 모아, 새 배열로 반환한다.


Solution 04

function removeSmallest(arr) {
  const indexOfSmallest = arr.indexOf(Math.min(...arr));
  let result = [...arr];
  
  result.splice(indexOfSmallest, 1);
  return result;
}

removeSmallest([1, 2, 3, 4]);  // [2, 3, 4]
removeSmallest([1, 1, 2, 3]);  // [1, 2, 3]
removeSmallest([4, 1, 1, 4]);  // [4, 1, 4]