我有两个长度相同的数组:
a = [12,21,21,13,13,13,13,31];
b = [4,7,4,6,2,9,4,1];
第一个数组是键,第二个数组是值,但如果重复键,则应将值分组到相应的键中而不是替换。 该对象应如下所示:
o = {
12: [4],
21: [7,4],
13: [6,2,9,4],
31: [1]
}
这就是我的尝试:
var o = {};
for ( var index in a) {
o[a[index]] = [];
o[a[index]].push(b[index]);
}
答案 0 :(得分:4)
试试这个:
var o = {};
for (var i = 0; i < b.length; i++) {
var key = a[i] + '';
if (key in o) {
o[key].push(b[i]);
}
else {
o[key] = [b[i]];
}
}
答案 1 :(得分:3)
循环中的第一行是破坏该插槽中的任何现有数组。如果还没有新数组,请尝试声明一个新数组:
var o = {};
for (var index = 0; index < a.length; index++) {
if(o[a[index]] == undefined) {
o[a[index]] = [];
}
o[a[index]].push(b[index]);
}
答案 2 :(得分:2)
不要使用for..in
循环遍历数组(除非它们是稀疏数组,你知道你正在做什么; details)。
除此之外,你是在正确的轨道上,但你必须在覆盖它之前检查数组是否已经存在。所以:
var o = {}, key, entry;
for (index = 0; index < a.length; ++index) {
// Get the key
key = a[index];
// Get the entry's array if it already exists
entry = o[key];
if (!entry) {
// It doesn't exist, create it and remember it in the object
o[key] = entry = [];
}
// Put this value in it
entry.push(b[index]);
}
或者几个小优化:
var o = {}, key, entry, len;
for (index = 0, len = a.length; index < len; ++index) {
// Get the key
key = a[index];
// Get the entry's array if it already exists
entry = o[key];
if (!entry) {
// It doesn't exist, create it and remember it in the object,
// including this value as we go
o[key] = [b[index]];
}
else {
// Already existed, add this value to it
entry.push(b[index]);
}
}
如果您使用的是启用了ES5的环境(或者包含ES5垫片),则可以使用forEach
:
var o = {};
a.forEach(function(key, index) {
var entry;
// Get the entry's array if it already exists
entry = o[key];
if (!entry) {
// It doesn't exist, create it and remember it in the object,
// including this value as we go
o[key] = [b[index]];
}
else {
// Already existed, add this value to it
entry.push(b[index]);
}
});
答案 3 :(得分:0)
以下是您可以在phpjs.com
中使用此功能的功能
function array_combine (keys, values) {
// Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values
var new_array = {}, keycount = keys && keys.length,
i = 0;
// input sanitation
if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count
return false;
}
// number of elements does not match if (keycount != values.length) {
return false;
}
for (i = 0; i < keycount; i++) { new_array[keys[i]] = values[i];
}
return new_array;
}