从键值对列表中创建数组[n,[v,..,z]]

时间:2014-01-22 22:34:08

标签: javascript arrays multidimensional-array

我有这个输入样本:

var c1 = "s_A_3";
var c2 = "s_B_10";
var c3 = "s_B_9";
var c4 = "s_C_18";
var c5 = "s_C_19";
var c6 = "s_C_20";

可以很容易地连接到:

var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];

我想把它转换成这样的多维数组:

var groupArray = [["A",[3]],["B",[10,9]],["C",[18,19,20]]];

这就像是一种卡片分类。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

也许是这样的:

function makeGroups(arr) {
    var result = [], prev;
    for(var i = 0; i < arr.length; i++) {
        var x = arr[i].split("_");
        if (prev !== x[0]) {
            prev = x[0];
            result.push([prev, []]);
        }
        result[result.length - 1][1].push(x[1]); // or .push(parseInt(x[1], 10))
    }
    return result;
}

var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
console.log(makeGroups(keypairs)); 
    // [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]] 

Demonstration


上述方法假设组是连续的(例如,所有B_元素一起出现)。如果您的输入可能出现故障,您可以调整此算法以将所有元素组合在一起,而不管它们在输入中的位置如何:

function makeGroups(arr) {
    var result = [], keys = {};
    for(var i = 0; i < arr.length; i++) {
        var x = arr[i].split("_");
        if (!(x[0] in keys)) {
            keys[x[0]] = [];
            result.push([x[0], keys[x[0]]]);
        }
        keys[x[0]].push(x[1]); // or .push(parseInt(x[1], 10))
    }
    return result;
}

var keypairs = ["A_3","B_10","C_18","C_19","C_20","B_9"];
console.log(makeGroups(keypairs));
    // [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]] 

Demonstration

答案 1 :(得分:0)

当您需要在JS程序中提及“键值对”时,通常最合适的是使用...键值对= D.

function solution(input) {
    var kvp = {},
        result = [];
    input.forEach(function (el) {
        var cut = el.split("_"),
            alpha = cut[0],
            numeric = cut[1],
            elsWithSameAlpha = kvp[alpha] = kvp[alpha] || [];
        elsWithSameAlpha.push(numeric);
    });
    Object.keys(kvp).forEach(function (key) {
        result.push([key, kvp[key]]);
    });
    return result;
}