我在jquery var str中有一个字符串,如下所示:
var str = 4-68,4-69,4-70,5-86,5-87,5-88,5-89,5-91,6-100,6-101
现在我想组织字符串并得到如下结果:
var result = 4(68,69,70)|5(86,87,88,89,91)|6(100,101)
看起来不太难。但是我无法在代码中准确地找出逻辑。
var dataRecord = '4-68,4-69,4-70,5-86,5-87,5-88,5-89,5-91,6-100,6-101';
var i = 1;
var first_item = [];
var second_item = [];
var final_item = [];
var agree_ref_data = dataRecord.agreement_ref_no;
var main_arr = agree_ref_data.split(',');
for (i = 0; i < main_arr.length; ++i) {
var second_arr = main_arr[i].split('-');
if (jQuery.inArray(second_arr[0], first_item) == -1) {
first_item.push(second_arr[0]);
//second_item.push(second_arr[1]);
}
if (jQuery.inArray(second_arr[0], first_item) !== -1) {
second_item.push(second_arr[1]);
} else {
final_result = second_item;
//second_item=[];
}
}
return final_result;
}
我如何得到我想要的结果?
答案 0 :(得分:2)
这是纯js.No jQuery所需的代码。我们首先用逗号分割字符串,然后迭代生成的数组,再用' - '分隔。然后将值存储为Map(为此使用普通的js对象)。 Rest只是迭代对象的键值对并按摩数据。
var dataRecord = '4-68,4-69,4-70,5-86,5-87,5-88,5-89,5-91,6-100,6-101';
var a = dataRecord.split(',');
var obj = {};
for(var i=0;i<a.length;i++){
var tmp = a[i].split('-');
if(typeof obj[tmp[0]] !== 'object'){
obj[tmp[0]] = [];
}
obj[tmp[0]].push(tmp[1]);
}
var result = '';
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " -> " + obj[key]);
result = result + key + '(' + obj[key].join() + ')|';
}
}
result = result.substr(0,result.length-1); // removing the last | character
答案 1 :(得分:1)
完整的工作代码命题(不需要jquery):
var str="4-68,4-69,4-70,5-86,5-87,5-88,5-89,5-91,6-100,6-101";
//##1 . Split by ,
//we have array of elements like 4-68
var arr=str.split(",");
//results temporary object
var results={};
//##2 .Create temporary object
for ( var el in arr){
//we have parts as [4, 68]
var parts=arr[el].split("-");
var main=parts[0];
var second=parts[1];
if (!results.hasOwnProperty(main)){
results[main]=second;//create new string for this main
}else //element with main exists so add next number
results[main]+=","+second;//concat to string
}
console.log("Temporary object structure:");
console.log(results);
//ok we have array with results but we need string
var resultsStr="";
//##3. Create final string
for ( var main in results){
if (resultsStr!="")
resultsStr+="|"; //add | not for first one
resultsStr+=main+"("+results[main]+")"; //add () to our string
}
console.log("Final string:");
console.log(resultsStr);
算法步骤:
即使主要数字的顺序不正确,算法也会运行。