반응형
Task
Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! )
The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value.
Mind the input validation.
Example
{ 6, 2, 1, 8, 10 } => 16 { 1, 1, 11, 2, 3 } => 6
If an empty value ( null, None, Nothing etc. ) is given instead of an array, or the given array is an empty list or a list with only 1 element, return 0.
solution
function sumArray(array) {
if(array ===null || array === undefined || array.length < 3) return 0
const maxNum = Math.max(...array)
const minNum = Math.min(...array)
let sum = 0;
for(let i=0; i<array.length; i++){
sum += array[i];
}
return sum - maxNum - minNum
}
sumArray(null) //0
sumArray([1,4,32,2]) //6
sumArray([1,2]) //0
Best solution
function sumArray(array) {
return Array.isArray(array) && array.length > 1
? array.reduce((s, n) => s + n, 0) - Math.min(...array) - Math.max(...array)
: 0
}
* Array.isArray() - 인자가 배열인지 판별
Array.isArray() - JavaScript | MDN
Array.isArray() 메서드는 인자가 Array인지 판별합니다.
developer.mozilla.org
* reduce()
array.reduce( callback [, initailValue])
array.reduce((누적, 현재, 인덱스, 배열) => {return ~ }, 초기값)
callback : 인자에 차례대로 4가지
- 누산기 (accmulator)
- 현재 처리할 요소 (currentValue)
- (옵션) 현재 처리할 요소의 인덱스 (초기값 제공한경우 0 , 아니면 1),
- (옵션) reduce를 호출한 배열
초기값 : 콜백의 최초 호출에서 첫 번째 인수에 제공하는 값.
초기값 제공하지 않으면 배열의 첫 번째 요소 사용.
빈 배열에서 초기값 없이 reduce() 호출하면 오류가 발생.
const arr = [1,2,3,4,5]
arr.reduce((누적, 현재) => {return 누적 += 현재}, 0)
// 15
Array.prototype.reduce() - JavaScript | MDN
reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
developer.mozilla.org
반응형
'Archive' 카테고리의 다른 글
[Next.js] getStaticPaths (Static Generation/fallback/동적 라우팅) (0) | 2023.01.17 |
---|---|
[Next.js] Pre-rendering 개념 & Static Generation(getStaticProps) (0) | 2023.01.08 |
[Regex] 정규 표현식 기초 (2) - 대괄호 / 부정부호 / 꺽쇠 (0) | 2022.12.05 |
[JS] JavaScript 개념 (자바스크립트 엔진, 원시형/참조형, Stack/Heap) (0) | 2022.11.28 |
[JS] JavaScript ES6 - var / let / const (0) | 2022.11.25 |