如何找到多个值存在于具有相同小数的数组中

时间:2017-09-04 09:33:58

标签: javascript arrays

这里我有一个数组,可以找到QNoMarks数组

中相同十进制密钥的多个值
var QNoMarks = [{"1.1":"4%"},
                {"1.2":"3%"},
                {"1.3":""},
                {"2":"2%"},
                {"3":"8%"},
                {"4.1":"5%"},
                {"4.2":""},
                {"5":"6%"},
                {"6.1":"2%"},
                {"6.2":"1%"}
               ];

如何查找多个值以相同的十进制值存在。在QNoMarks

例如

以下的输出
{"1.1":"4%"},{"1.2":"3%"},{"1.3":""} // multiple value found in 1.1 and 1.2
{"2":"2%"} // no multiple value
{"3":"8%"} // no multiple value
{"4.1":"5%"},{"4.2":""}, // no multiple value
{"5":"6%"}, // no mulitple value
{"6.1":"2%"},{"6.2":""},{"6.3":"1%"} // multiple value found in 6.1 and 6.3

3 个答案:

答案 0 :(得分:0)

您可以通过以下方式执行此操作

var QNoMarks = [{"1.1":"4%"},
                {"1.2":"3%"},
                {"1.3":""},
                {"2":"2%"},
                {"3":"8%"},
                {"4.1":"5%"},
                {"4.2":""},
                {"5":"6%"},
                {"6.1":"2%"},
                {"6.2":"1%"}
               ];
let result = {};               
for(let element of QNoMarks){
    for(let property in element){
        let prefix = property.match(/(\d+)\.?/)[1];
        result[prefix] = result[prefix] || [];
        result[prefix].push(element);
    }
}

console.log(result);

这里我将所有在小数点前具有相同编号的对象分组。我正在使用正则表达式来获取值

答案 1 :(得分:0)

您可以按键的整数值进行分组,并对相同的组使用哈希表。



var data = [{ "1.1": "4%" }, { "1.2": "3%" }, { "1.3": "" }, { "2": "2%" }, { "3": "8%" }, { "4.1": "5%" }, { "4.2": "" }, { "5": "6%" }, { "6.1": "2%" }, { "6.2": "1%" }],
    groups = Object.create(null),
    result = [];
    
data.forEach(function (o) {
    var key = Math.floor(Object.keys(o)[0]);
    if (!groups[key]) {
        groups[key] = [];
        result.push(groups[key]);
    }
    groups[key].push(o);
});

console.log(groups); // as object with group keys
console.log(result); // as array

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

使用reduce:

将它们按整数分组



let QNoMarks = [{"1.1":"4%"},{"1.2":"3%"},{"1.3":""},{"2":"2%"}, {"3":"8%"}, {"4.1":"5%"}, {"4.2":""}, {"5":"6%"}, {"6.1":"2%"}, {"6.2":"1%"}];
let res = QNoMarks.reduce((a, b) => {
  let key = Math.floor(Object.keys(b)[0]);
  a[key] = (a[key] || []).concat(b);
  return a;
}, Object.create(null));
console.log(res);