B T
B T

Reputation: 161

Javascript Multidimensional Array into single arrays

I am a JS newbie and having a hard time figuring out how to run a function with what I have..

The function:

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;
};

I have a multidimensional array like below that I want to pull out the third element to run through the function.

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

So I'm trying to figure out how to get the array to be single arrays like below

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

or ideally tweak the function so that the multidimensional array can stay in tact.

Upvotes: 1

Views: 1593

Answers (2)

Mike Trpcic
Mike Trpcic

Reputation: 25649

// 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(", ");
}

With the above code, your output would look like the following:

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

Upvotes: 0

iConnor
iConnor

Reputation: 20189

This is kinda too localized but something like this.

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

Upvotes: 2

Related Questions