2016-09-19 6 views
0

ここに質問するのは大丈夫な質問です... モードを見つけるための関数の作成に少し助けがありました。しかし、今私はそれを理解するための少しの助けが必要です... (私は全く新しいプログラミングです) データは、 "情報"を保持して、別のファイルの複数の配列が含まれています。モードを見つけるための関数の理解

let mode = function(data) { 
    data.sort(function(a, b) { 
    return a - b;  
    }); 
    let mode = {}, 
    highestOccurrence = 0, 
    modes = []; 
    data.forEach(function(element) { 
    if (mode[element] === undefined) { 
     mode[element] = 1; 
    } else { 
     mode[element]++; 
    } 
    if (mode[element] > highestOccurrence) { 
     modes = [element]; 
     highestOccurrence = mode[element]; 
    } else if (mode[element] === highestOccurrence) { 
     modes.push(element); 
     highestOccurrence = mode[element]; 
    } 
    }); 
    return modes; 
}; 

まず、関数をソートするだけで、数字が順番に表示されるようになります。しかし、誰かが私が他の機能を理解するのを助けるような親切なことができますか?

+0

は 'data.forEach'に' data1.forEach'を修正してください役立ちます

let mode = function(data) { data.sort(function(a, b) { return a - b; }); let mode = {}, highestOccurrence = 0, modes = []; // This loops through data array (It should be data here and not data1) data.forEach(function(element) { // Here you check if the mode object already have that element key, // setting the first occurence or incrementing it if (mode[element] === undefined) { mode[element] = 1; } else { mode[element]++; } // After that it checks if that mode has the higher occurence if (mode[element] > highestOccurrence) { // If it has the higher occurence it sets the modes to an array with // that element and the highestOccurrence value to that value modes = [element]; highestOccurrence = mode[element]; } else if (mode[element] === highestOccurrence) { // If it has the same number of occurences it just adds that mode to // the modes to be returned modes.push(element); highestOccurrence = mode[element]; } }); return modes; }; 

希望。 –

答えて

1

あなたが提供したコードでしか推論できないいくつかのコメントを追加しました。あなたはあなたが持っているデータの種類と達成しようとしているもののようなあなたの質問にいくつかの文脈を提供することができ、役に立つかもしれない例を提供することができます。これはあなた

+0

たとえば、私はこの配列を持っています:([20,4,1,2、-1,2,13,2,1,5,5,5,5,20,20]) そして私は最大値、最小値、平均値、中央値、モードおよび範囲を見つけるための関数。 あなたが追加したコメントは本当にありがとう! – babyCoder

+0

@taguenizy ...あなたはそれを試したことがありません - OPの例が行うように、 'data1'と渡された' data'の間に無関係なので、コードはエラーを投げます。 –

+0

@PeterSeliger私はそれがタイプミスであると仮定しました。彼はそれが何をしているのか理解したかったのです。しかし私は私の応答でそれを修正します – taguenizy

関連する問題