2016-10-13 13 views
1

での文字列の合計を数えるが、この長い文字列を分割し、同じ文字列のx前に数をsuming持つすべてのオカレンスCOUT私は苦労してる文字列の分割と、私は文字列にしようとしている数

<div id="all">3xOrange;2xBlue;1xRed;1xRed;1xRed;1xOrange;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xOrange;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;20xBlue;33xRed;20xBlue;33xRed;2xBlue;3xRed;51xBlue;51xRed;</div> 

<b id="total"></b> 

を分割しますこのコード:

var obj = {}; 

$("#all").text().split(";").forEach(function(text){ 
    if (text != ""){ 
    var part = text.split("x"); 
    obj[part[1]] = obj[part[1]] != undefined ? obj[part[1]]+1 : parseInt(part[0]); 
    } 
}); 
for (key in obj) { 
    $("#total").append(obj[key] +"×"+ key + "; "); 
} 

問題は、アルが、それは理論的に動作しますが、しかし、文字列分割の一部の上に掲示一つはsumingによって無視されるような文字列が長すぎるということです。 合計の合計がOrange Red and Blueで間違っています。

Codepen code here!

私はきちんと私の文字列分割を合計し、このfuncionalityを修正することができますどのように、助けてください。私はx ONT ;と一瞬で上splitをしましたし、合計で最初の行を追加します

まず:

答えて

0

はこのような何かを試してみてください。

合計で各キーを保存するための連想配列を作成します。そしてObject.keys(array).forEach(function(key, index) {},array);方法やfor(var key in array){}

var array = $("#all").text().split(';'); 
 
var total=0; 
 
var colorarray = new Array(); 
 
$.each(array,function(key,value){ 
 
if(value!='') 
 
{ 
 
    if(colorarray[value.split("x")[1]]==undefined) 
 
    { 
 
    colorarray[value.split("x")[1]]=0; 
 
    } 
 
    
 
    var itemnumber = parseInt(value.split("x")[0]); 
 
    colorarray[value.split("x")[1]]+=(itemnumber); 
 
    total+=(itemnumber); 
 
} 
 
}); 
 

 
for(var key in colorarray) 
 
{ 
 
    $("#total").append("<div>"+key+" : "+colorarray[key]+"</div>"); 
 
}; 
 

 
$("#total").append("<div>total :"+total+"</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="all">3xOrange;2xBlue;1xRed;1xRed;1xRed;1xOrange;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xOrange;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;20xBlue;33xRed;20xBlue;33xRed;2xBlue;3xRed;51xBlue;51xRed;</div> 
 

 
<b id="total"></b>

+0

とこの配列のループは、これは実際には非常にうまく動作しますが、私はまだこのような場合(xOrange、xBlue、XRED)で、文字列分割の第二の部分を必要とします私の意図は、それぞれのオレンジ、青と赤の合計を得ることでした –

+0

@ P.Ishtik私の更新を確認 – Alexis

+0

あなたはそれをやった:)!チャームのように働いて、ありがとう! –

関連する問題