简体   繁体   English

匹配相同值的十进制数字以推入数组

[英]Matches same value decimal numbers to push in to an array

i have a Srings inside of array 我在数组内部有一个Srings

var QNo = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"];

Need to change QNo in array of objects with matching decimals like this 需要更改具有匹配小数的对象数组中的QNo像这样

var result = [["1.1","1.2","1.3"],["2.1","2.2"],["3.1","3.2","3.3"],["4.1","4.2"]];

i hv tried this kind of code 我试过这种代码

for (var j = 0; j < QNo.length ; j++) {
     if ( QNo[j].match(/.*(?=\.)/g) ) {
      result.push(QNo[j]);
     }
}

After the Match i don't get any idea to push decimals values as object 比赛结束后,我不知道将小数点值作为对象

You can use reduce to go over all the items in the array and group them by their int value using an object where each item will go into the relevant key in that object (the key is based on the int value): 您可以使用reduce遍历数组中的所有项目,并使用一个object按它们的int值对它们进行分组,其中每个项目都将进入该object中的相关key (该键基于int值):

 var QNo = ["1.1","1.2","1.3","2.1","2.2","3.1","3.2","3.3","4.1","4.2"]; var reduced = QNo.reduce((res, item) => { if (res.hasOwnProperty(parseInt(item))) { res[parseInt(item)].push(item) } else { res[parseInt(item)] = [item] } return res; }, {}); console.log(reduced); console.log(Object.values(reduced)); 

You could take the left part of the splitted value and check if the last value is in the same group -- then push the value to the group. 您可以将分割后的值的左侧取整,并检查最后一个值是否在同一组中-然后将值推入该组中。 If not, then build a new group. 如果不是,则建立一个新组。

 var qNo = ["1.1", "1.2", "1.3", "2.1", "2.2", "3.1", "3.2", "3.3", "4.1", "4.2"], result = qNo.reduce(function (r, a, i, aa) { function left(a) { return (a || '').split('.')[0]; } if (left(a) === left(aa[i - 1])) { r[r.length - 1].push(a); } else { r.push([a]); } return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

For unsorted values, you could use a hash table and sort the result later. 对于未排序的值,可以使用哈希表并在以后对结果进行排序。

 var qNo = ["1.1", "3.1", "1.2", "1.3", "2.1", "3.2", "3.3", "4.1", "2.2", "4.2"], hash = Object.create(null), result = qNo.reduce(function (r, a, i, aa) { function left(a) { return (a || '').split('.')[0]; } var key = left(a); if (!hash[key]) { hash[key] = []; r.push(hash[key]); } hash[key].push(a); return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM