Development Tip

숫자 배열의 합을 찾는 방법

yourdevel 2020. 9. 30. 11:36
반응형

숫자 배열의 합을 찾는 방법


배열이 주어지면 [1, 2, 3, 4]요소의 합계를 어떻게 찾을 수 있습니까? (이 경우 합계는입니다 10.)

$.each유용 하다고 생각 했지만 어떻게 구현해야할지 모르겠습니다.


권장 (기본값으로 축소)

Array.prototype.reduce 를 사용하여 배열을 반복하여 현재 요소 값을 이전 요소 값의 합계에 추가 할 수 있습니다.

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)

기본값 없음

TypeError가 발생합니다.

console.log(
  [].reduce((a, b) => a + b)
)

ES6의 화살표 기능 이전

console.log(
  [1,2,3].reduce(function(acc, val) { return acc + val; }, 0)
)

console.log(
  [].reduce(function(acc, val) { return acc + val; }, 0)
)

숫자가 아닌 입력

숫자가 아닌 입력이 가능한 경우 처리 할 수 ​​있습니까?

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => a + b)
)

let numOr0 = n => isNaN(n) ? 0 : n

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => 
    numOr0(a) + numOr0(b))
)

권장되지 않는 위험한 평가 사용

eval사용 하여 JavaScript 코드의 문자열 표현을 실행할 수 있습니다 . Array.prototype.join 함수를 사용하여 배열을 문자열로 변환하고 [1,2,3]을 "1 + 2 + 3"로 변경하여 6으로 평가합니다.

console.log(
  eval([1,2,3].join('+'))
)

//This way is dangerous if the array is built
// from user input as it may be exploited eg: 

eval([1,"2;alert('Malicious code!')"].join('+'))

물론 경고를 표시하는 것이 최악의 상황은 아닙니다. 내가 이것을 포함시킨 유일한 이유는 그것이 명확하지 않다고 생각하기 때문에 Ortund의 질문에 대한 답변입니다.


에서 리스프 에 대해 정확하게 작업 할 수 this'd reduce. 다음과 같은 코드가 표시됩니다.

(reduce #'+ '(1 2 3)) ; 6

다행히 JavaScript에는 reduce! 불행히도은 +함수가 아니라 연산자입니다. 그러나 우리는 그것을 예쁘게 만들 수 있습니다! 여기보세요 :

const sum = [1, 2, 3].reduce(add,0); // with initial value to avoid when the array is empty

function add(accumulator, a) {
    return accumulator + a;
}

console.log(sum); // 6

예쁘지 않나요? :-)

더 좋습니다! ECMAScript 2015 (일명 ECMAScript 6 )를 사용하는 경우 다음과 같이 예뻐질 수 있습니다.

const sum = [1, 2, 3].reduce((partial_sum, a) => partial_sum + a,0); 
console.log(sum); // 6

왜 줄이지 않습니까? 일반적으로 다소 직관적이지 않지만 합계를 찾는 데 사용하는 것은 매우 간단합니다.

var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);

var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }

var total = 0;
$.each(arr,function() {
    total += this;
});

이것은 모든 항목을 반복하고 각 반복마다- sum변수 에 추가함으로써 가능합니다 .

var array = [1, 2, 3];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]);

JavaScript는 블록 범위를 알지 못하므로 sum액세스 할 수 있습니다.

console.log(sum); // => 6

위와 동일하지만 주석을 달고 간단한 기능으로 준비했습니다.

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}

Lodash를 사용하는 경우 sum 함수를 사용할 수 있습니다.

array = [1, 2, 3, 4];
sum = _.sum(array); // sum == 10

arr.reduce(function (a, b) {
    return a + b;
});

참조 : Array.prototype.reduce ()


// Given array 'arr'
var i = arr.length;
var sum = 0;
while (--i) sum += arr[i];

eval()방법을 사용한 3.604ms / 실행 및 (i, length, ++에 대한 표준을 사용한 실행 당 2.151ms에 비해) 평균 1.57ms / 실행 (100 개의 임의 정규 숫자 배열에서 1000 개 이상의 실행으로 측정 됨)이 소요됩니다. ) 루프.

방법론 참고 :이 테스트는 Google Apps Script 서버에서 실행되었으므로 자바 스크립트 엔진은 Chrome과 거의 동일합니다.

편집 : 매 실행마다 0.12ms --ii--저장하는 대신 (i--는 1.7입니다)

편집 : 성스러운 욕설,이 전체 게시물을 신경 쓰지 마십시오. 위에서 언급 한 reduce () 메서드를 사용합니다. 단 1ms / run입니다.


reduceRight를 사용할 수도 있습니다.

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

결과는 21로 출력됩니다.

참조 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight


좋아요, 아래에이 배열이 있다고 상상해보세요.

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

여기에서 포괄적 인 답을 찾을 수 없었기 때문에 다양한 방법살펴 보겠습니다 .

1) 내장 reduce () 사용

function total(arr) {
  if(!Array.isArray(arr)) return;
  return arr.reduce((a, v)=>a + v);
}

2) for 루프 사용

function total(arr) {
  if(!Array.isArray(arr)) return;
  let totalNumber = 0;
  for (let i=0,l=arr.length; i<l; i++) {
     totalNumber+=arr[i];
  }
  return totalNumber;
}

3) while 루프 사용

function total(arr) {
  if(!Array.isArray(arr)) return;
  let totalNumber = 0, i=-1;
  while (++i < arr.length) {
     totalNumber+=arr[i];
  }
  return totalNumber;
}

4) 어레이 forEach 사용

function total(arr) {
  if(!Array.isArray(arr)) return;
  let sum=0;
  arr.forEach(each => {
    sum+=each;
  });
  return sum;
};

다음과 같이 부릅니다.

total(arr); //return 10

이와 같은 프로토 타입을 Array에 사용하지 않는 것이 좋습니다.


나 같은 기능성 원 라이너를 찾는 분? 이것을 가지고 가십시오 :

sum= arr.reduce(function (a, b) {return a + b;}, 0);

재미있는 접근 방식 :

eval([1,2,3].join("+"))

표준 JavaScript 솔루션 :

var addition = [];
addition.push(2);
addition.push(3);

var total = 0;
for (var i = 0; i < addition.length; i++)
{
    total += addition[i];
}
alert(total);          // Just to output an example
/* console.log(total); // Just to output an example with Firebug */

이것은 나를 위해 작동합니다 (결과는 5이어야 함). 이런 종류의 솔루션에 숨겨진 단점이 없기를 바랍니다.


저는 자바 스크립트와 일반적인 코딩을 사용하는 초보자이지만 배열의 숫자를 합산하는 간단하고 쉬운 방법은 다음과 같습니다.

    var myNumbers = [1,2,3,4,5]
    var total = 0;
    for(var i = 0; i < myNumbers.length; i++){
        total += myNumbers[i];
    }

기본적으로 기본 제공 함수를 사용하지 않는 솔루션을 많이 보지 못했고이 방법은 작성하고 이해하기 쉽기 때문에 기여하고 싶었습니다.


var totally = eval(arr.join('+'))

이렇게하면 모든 종류의 이국적인 것들을 배열에 넣을 수 있습니다.

var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]

나는 단지 반 농담입니다.


짧은 JavaScript 코드가이 작업을 수행합니다.

var numbers = [1,2,3,4];
var totalAmount = 0;

for (var x = 0; x < numbers.length; x++) {

    totalAmount += numbers[x];
}

console.log(totalAmount); //10 (1+2+3+4)

A few people have suggested adding a .sum() method to the Array.prototype. This is generally considered bad practice so I'm not suggesting that you do it.

If you still insist on doing it then this is a succinct way of writing it:

Array.prototype.sum = function() {return [].reduce.call(this, (a,i) => a+i, 0);}

then: [1,2].sum(); // 3

Note that the function added to the prototype is using a mixture of ES5 and ES6 function and arrow syntax. The function is declared to allow the method to get the this context from the Array that you're operating on. I used the => for brevity inside the reduce call.


Here's an elegant one-liner solution that uses stack algorithm, though one may take some time to understand the beauty of this implementation.

const getSum = arr => (arr.length === 1) ? arr[0] : arr.pop() + getSum(arr);

getSum([1, 2, 3, 4, 5]) //15

Basically, the function accepts an array and checks whether the array contains exactly one item. If false, it pop the last item out of the stack and return the updated array.

The beauty of this snippet is that the function includes arr[0] checking to prevent infinite looping. Once it reaches the last item, it returns the entire sum.


You can combine reduce() method with lambda expression:

[1, 2, 3, 4].reduce((accumulator, currentValue) => accumulator + currentValue);

Use reduce

let arr = [1, 2, 3, 4];

let sum = arr.reduce((v, i) => (v + i));

console.log(sum);


No need to initial value! Because if no initial value is passed, the callback function is not invoked on the first element of the list, and the first element is instead passed as the initial value. Very cOOl feature :)

[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1

Use a for loop:

const array = [1, 2, 3, 4];
let result = 0;

for (let i = 0; i < array.length - 1; i++) {
  result += array[i];
}

console.log(sum); // Should give 10

Or even a forEach loop:

const array = [1, 2, 3, 4];
let result = 0;

array.forEach(number => {
  result += number;
})

console.log(result); // Should give 10

For simplicity:

const array = [10, 20, 30, 40];
const add = (a, b) => a + b
const result = array.reduce(add);

console.log(result); // Should give 100

Cool tricks here, I've got a nit pick with a lot of the safe traditional answers not caching the length of the array.

function arraySum(array){
  var total = 0,
      len = array.length;

  for (var i = 0; i < len; i++){
    total += array[i];
  }

  return total;
};

var my_array = [1,2,3,4];

// Returns 10
console.log( arraySum( my_array ) );

Without caching the length of the array the JS compiler needs to go through the array with every iteration of the loop to calculate the length, it's unnecessary overhead in most cases. V8 and a lot of modern browsers optimize this for us, so it is less of a concern then it was, but there are older devices that benefit from this simple caching.

If the length is subject to change, caching's that could cause some unexpected side effects if you're unaware of why you're caching the length, but for a reusable function who's only purpose is to take an array and add the values together it's a great fit.

Here's a CodePen link for this arraySum function. http://codepen.io/brandonbrule/pen/ZGEJyV

It's possible this is an outdated mindset that's stuck with me, but I don't see a disadvantage to using it in this context.


Those are really great answers, but just in case if the numbers are in sequence like in the question ( 1,2,3,4) you can easily do that by applying the formula (n*(n+1))/2 where n is the last number


Object.defineProperty(Object.prototype, 'sum', {
    enumerable:false,
    value:function() {
        var t=0;for(var i in this)
            if (!isNaN(this[i]))
                t+=this[i];
        return t;
    }
});

[20,25,27.1].sum()                 // 72.1
[10,"forty-two",23].sum()          // 33
[Math.PI,0,-1,1].sum()             // 3.141592653589793
[Math.PI,Math.E,-1000000000].sum() // -999999994.1401255

o = {a:1,b:31,c:"roffelz",someOtherProperty:21.52}
console.log(o.sum());              // 53.519999999999996

This is much easier

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)

i saw all answers going for 'reduce' solution

var array = [1,2,3,4]
var total = 0
for (var i = 0; i < array.length; i++) {
    total += array[i]
}
console.log(total)

A simple method example:

function add(array){
    var arraylength = array.length;
    var sum = 0;
    for(var timesToMultiply = 0; timesToMultiply<arraylength; timesToMultiply++){
        sum += array[timesToMultiply];
    }

    return sum;
}

console.log(add([1, 2, 3, 4]));

try this...

function arrSum(arr){
    total = 0;  
    arr.forEach(function(key){
        total = total + key;            
    });
    return total;
}

참고URL : https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers

반응형