简单的商品去重复和统计金额
var oTti=document.querySelector('#initial');
var oTtr=document.querySelector('#result');
var oBtn=document.querySelector('button');
function sort(arr,arr2) {
for(var i=0;i
arr2[i]=arr2[i]*(arr[i].substring(arr[i].indexOf('-')+1,arr[i].length-1));
}
return arr2;
}
oBtn.onclick=function () {
var str = oTti.value;
var arr = str.split(' ');
var arr1 = [];
var arr2 = [];
var arr3=[];
var hash=[];
for (var i =0; i < arr.length; i++) {
for (var j = i+1; j < arr.length; j++) {
if(arr[i]===arr[j]){
++i;
}
}
hash.push(arr[i]);
}
//初始化
for (var i =0; i < hash.length; i++){
arr1[i]=0;
arr3[i]=0;
}
//然后计数统计重复个数
for (var i =0; i < hash.length; i++)
for(var j=0;j
if(hash[i]==arr[j]){
arr1[i]++;
arr3[i]++;
}
}
arr2=sort(hash,arr1);//计算重复的金额
//去减号后面的数据
for(var i=0;i
hash[i]=hash[i].substring(0,hash[i].indexOf('-'));
}
//拼接
for(var i=0;i
hash[i]=hash[i]+'('+arr3[i]+')'+' '+'¥'+arr2[i];
}
//计算总金额
var sum=0;
for(var i=0;i
sum+=arr2[i];
}
hash.push('总共:¥'+sum);
str=hash.join('-');
oTtr.value=str.replace(/-/g,'\n');
}