📌 [요건] :
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.
[10, 343445353, 3453445, 3453545353453] should return 3453455.
==> 가장 작은 숫자 2개를 더한 값을 return하라
✍ [코드작성]
function sumTwoSmallestNumbers(arr) { let newarr = arr.sort( function(a, b) { return a - b; // 오름차순: a - b, 내림차순 : b - a } ); console.log(newarr); let minNum = newarr.slice(0,2); let sum = minNum[0] + minNum[1]; console.log(sum); return sum; } sumTwoSmallestNumbers([5, 8, 12, 19, 22]);
✔ [문제]
sort()는 기본적으로 유니코드 포인트를 기본으로 배열을 정렬한다.
매개변수 : compareFunction
반환값 : 정렬한 배열 (원배열이 정렬되는것은 아님)
compareFunction으로 문자열, 숫자를 오름/내림차순으로 정렬 가능.
참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort