Javascript:解析一个字符串并在字符串中找到相同的命名项并将它们合计

时间:2016-07-08 13:43:18

标签: javascript

我有一个以逗号分隔的字符串(它会有所不同,并不总是包含相同的数据),我需要找到所有相同的项目,然后统计出现的数字。当字符串从Feed中拉出时,字符串将始终如下所示:

代数(2.50小时),代数(2.50小时),代数(2.50小时),代数(2.50小时),代数(2.50小时),代数(2.50小时),代数(6.50小时),代数(2.50小时) ,代数(2.50小时),竞技(出勤)(2.50小时),竞技(出勤)(2.50小时),竞技(出勤)(6.50小时),竞技(出勤)(2.50小时),竞技(出勤)(2.50小时) ),竞技(出勤)(2.50小时),竞技(出勤)(2.50小时),竞技(出勤)(2.50小时),竞技(出勤)(2.50小时)

我需要列出每个班级类型,如代数或竞技(出勤),以及可能的总学分数。因此,对于这个例子,我最终需要得到一个我可以显示的变量,“代数(26.50小时),运动(出勤)(26.50小时)。”在这个特定的例子中,两个班的时间都是相同但但并非总是如此。

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:1)

var str = 'Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (6.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (6.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours)'
str.split(',').map(function(s){
  return {
    hours: s.match(/\((\d\.\d)+.+\)$/)[1].trim(),
    title: s.match(/^(.+)\(/)[1].trim()
  };
}).reduce(function(prev, current){
  if (!prev[current.title]) {
    prev[current.title] = 0;
  }
  prev[current.title] += parseFloat(current.hours);
  return prev;
}, {})

jsfiddle

答案 1 :(得分:0)

首先,拆分你的字符串。     var split = string.split(',');

创建一个数组。     var array = [];

然后遍历拆分以获取所有值

for (var i=0;i<split.length;i++){
   array.push(split[i][0]);
  }

使用独特的数组函数(需要添加它,见下文

var uniqueArray=array.unique();

接下来循环遍历唯一数组以推送总值(需要循环内的循环)

  var totals =[];
  for(var u=0;u<uniqueArray.length;u++){
    var totalThis=0;
    for(var i=0;i<split.length;i++){
     if(uniqueArray[u]!=split[i][0]){continue;} 
     totalThis+=1;
    }
   totals.push([uniqueArray[u], totalThis]) 
} 

将此代码放在您的函数之外

Array.prototype.unique = function() {
    var arr = [];
    for(var i = 0; i < this.length; i++) {
        if(!arr.contains(this[i])) {
            arr.push(this[i]);
        }
    }
    return arr; 
}

答案 2 :(得分:0)

您可以这样做:

var s = "Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (6.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (6.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours)"
var splitResults = s.split(',');
var results = {};

for (var i = 0; i < splitResults.length; i++) {
    // Get the item name by looking for anything before the ( and stripping the extra space
    var item = splitResults[i].replace(/(.*?)\(.*/i, "$1").replace(/\s/g, '');

    // Get the item hours by finding the digit, including decimal point inside parenthesis
    var hours = splitResults[i].replace(/.*\(([0-9\.]+)\shours\)/i, "$1");

    // The iteem doesn't already exists in the struc
    if (results[item] === undefined) {
        results[item] = parseFloat(hours);
    }
    else {
        // Add the hours to the existing item
        results[item] += parseFloat(hours);
    }
}

// Outputs: Object {Algebra: 26.5, Athletic: 26.5}
console.log(results);

答案 3 :(得分:0)

看看这个

var str = "Algebra (6.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Athletic (Attendance) (2.50 hours), Athletic (Attendance) (2.50 hours)";

var arr = str.split(",");
arr = arr.map(function(item,i,self){
    var object = item.trim();
  return {
    subj: object.split(" ")[0],
    time: object.split("").reverse().join("").split(" ")[1].split("").reverse().join("").split("(")[1]
  }
});



console.log(arr);

答案 4 :(得分:0)

以下是一种方法,将每个课程和小时总数添加到无序列表中。

参见JSFiddle示例:https://jsfiddle.net/khristopherallen/8p868nwf/

var feedData="Algebra (2.50 hours), Algebra (4.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Algebra (3.50 hours), Algebra (2.50 hours), Algebra (6.50 hours), Algebra (2.50 hours), Algebra (2.50 hours), Athletic (Attendance) (5.50 hours), Science (2.25 hours), Athletic (Attendance) (6.50 hours), Athletic (Attendance) (2.50 hours), Reading (2.50 hours), Athletic (Attendance) (2.50 hours), History (2.50 hours), History (6.50 hours), Athletic (Attendance) (2.50 hours)";

function parseFeedData(data){
    var returnValue = "";
    var classes = new Object();
    var splitItems = data.split(', ');

    $(splitItems).each(function(index,value){
         var className = value.substring(0,value.lastIndexOf('(')).trim();
         var classHours = value.substring(value.lastIndexOf('('),value.length).trim().split(' ')[0].substring(1);

        if (classes[className] == null){
            classes[className] = new Object();
            classes[className].name = className;
        }

        if (classes[className].hours == null){
            classes[className].hours = 0;
        }

        if (parseFloat(classHours) != NaN){
            classes[className].hours += parseFloat(classHours);
        }
    });
    for (var i in classes){
        $('#classes').append("<li>" + classes[i].name  + ": " + classes[i].hours + " hours</li>")
    }
}

$(document).ready(function(){
    parseFeedData(feedData);
});