[英]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.. 我是JS新手,很难弄清楚如何使用已有的函数运行函数。
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. 或理想情况下调整功能,以便多维数组可以保持原样。
This is kinda too localized but something like this. 这有点太本地化,但类似这样。
var newArray1 = animalcount[0][2].split(', ');
var newArray2 = animalcount[1][2].split(', ');
// 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"]
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.