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

时间:2017-09-02 14:50:42

标签: javascript arrays arraylist

我在数组中有一个Srings

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

需要更改具有匹配小数的对象数组中的 QNo

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

我试过这种代码

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

比赛结束后,我不知道将小数值作为对象推送

2 个答案:

答案 0 :(得分:1)

您可以使用reduce覆盖数组中的所有项目,并使用object按其int值对其进行分组,其中每个项目都会进入该对象中的相关key (关键是基于int值):

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以获取拆分值的左侧部分并检查最后一个值是否在同一组中 - 然后将值推送到该组。如果没有,那么建立一个新的组。

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

对于未排序的值,您可以使用哈希表并稍后对结果进行排序。

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;