Javascript将多维数组转换为单个数组

时间:2013-10-17 18:00:27

标签: javascript arrays multidimensional-array

我是一名JS新手,很难搞清楚如何使用我所拥有的功能运行...

功能:

function compressArray(original) {

    var compressed = [];
    // make a copy of the input array
    var copy = original.slice(0);

    // first loop goes over every element
    for (var i = 0; i < original.length; i++) {

        var myCount = 0;    
        // loop over every element in the copy and see if it's the same
        for (var w = 0; w < copy.length; w++) {
            if (original[i] == copy[w]) {
                // increase amount of times duplicate is found
                myCount++;
                // sets item to undefined
                delete copy[w];
            }
        }

        if (myCount > 0) {
            var a = new Object();
            a.value = original[i];
            a.count = myCount;
            compressed.push(a);
        }
    }

    return compressed;
};

我有一个像下面这样的多维数组,我想拉出第三个元素来运行该函数。

var animalcount = [
        [2.8, 20, "dog, cat, bird, dog, dog"],
        [4.2, 22, "hippo, panda, giraffe, panda"],
        [3.7, 41, "snake, alligator, tiger, tiger"]
                ];

所以我想弄清楚如何让数组成为单个数组,如下面的

var newArray1 = ("dog", "cat", "bird", "dog", dog");
var newArray2 = ("hippo", "panda", "giraffe", "panda");

或理想地调整函数,以便多维数组可以保持原状。

2 个答案:

答案 0 :(得分:2)

这有点过于本地化,但有点像这样。

var newArray1 = animalcount[0][2].split(', ');
var newArray2 = animalcount[1][2].split(', ');

答案 1 :(得分:0)

// Your input array
var animalcount = [
    [2.8, 20, "dog, cat, bird, dog, dog"],
    [4.2, 22, "hippo, panda, giraffe, panda"],
    [3.7, 41, "snake, alligator, tiger, tiger"]
];

// Your empty output array
var results = [];

// For every record in your input array
for(var i = 0; i < animalcount.length; i++){
    // Get the string list, split it on the commas, and store the
    // result in your output array at the same index
    results[i] = animalcount[i][2].split(", ");
}

使用上面的代码,您的输出将如下所示:

results = [
    ["dog", "cat", "bird", "dog", "dog"],
    ["hippo", "panda", "giraffe", "panda"],
    ["snake", "alligator", "tiger", "tiger"]
];