184
153

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[JavaScript] 配列(Array)の合計値, 平均値, 中央値をモダンに求める

Last updated at Posted at 2014-06-26

よかったらこっちで見てください -> http://phiary.me/javascript-array-sum-average-median



モダンといっても ECMAScript 5 から追加されたメソッドを使ってるってだけです...

サンプルはこちら.

js-logo.png

合計値を求める

イケてない実装

普通に for 文回す.

var sum  = function(arr) {
	var sum = 0;
	for (var i=0,len=arr.length; i<len; ++i) {
		sum += arr[i];
	};
	return sum;
};

var arr = [1, 2, 3, 4, 5];
console.log( sum(arr) ); // 15

ちょっと今風

Array.prototype.forEach 使ってます.

var sum  = function(arr) {
	var sum = 0;
	arr.forEach(function(elm) {
		sum += elm;
	});
	return sum;
};

var arr = [1, 2, 3, 4, 5];
console.log( sum(arr) ); // 15

モダンな感じ

Array.prototype.reduce ってやつ使ってます.
隣り合う要素に関数を適応していく関数です.

var sum  = function(arr) {
    return arr.reduce(function(prev, current, i, arr) {
        return prev+current;
    });
};

var arr = [1, 2, 3, 4, 5];
console.log( sum(arr) ); // 15

さらにモダンっというか多機能

関数渡せるようにしてみました.
fn を省略した場合普通のが呼ばれます.

var sum = function(arr, fn) {
	if (fn) {
		return sum(arr.map(fn));
	}
	else {
		return arr.reduce(function(prev, current, i, arr) {
				return prev+current;
		});
	}
};

var arr = [1, 2, 3, 4, 5];
console.log( sum(arr) ); // 15
console.log( sum(arr, function(elm) {
	return elm*2;
})); // 30
var arr2 = ['a', 'b', 'c'];
console.log( sum(arr2) ); // abc
console.log( sum(arr2, function(elm) {
	return elm.charCodeAt();
}) ); // 249

ついでに平均値と中央値求めるのも作ってみた

平均値

sum 使い回し.

var average = function(arr, fn) {
    return sum(arr, fn)/arr.length;
};
var arr = [1, 2, 3, 4, 5];
console.log( average(arr) );    // 3

中央値

fn は sort 用関数です.

var median = function(arr, fn) {
    var half = (arr.length/2)|0;
    var temp = arr.sort(fn);

    if (temp.length%2) {
        return temp[half];
    }

    return (temp[half-1] + temp[half])/2;
};

console.log(median([1, 2, 3, 4, 5]));       // 3
console.log(median([1, 2, 3, 4, 5, 6]));    // 3.5
console.log(median([6, 6, 1, 2, 3, 4, 5])); // 4

Qiita もっと下書き残せるようにしてくれー!><

184
153
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
184
153

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?