Reputation: 5409
Let's say I have two arrays:
var a = [[1, 10], [2, 10], [3, 10], [4, 10], [5, 10]];
var b = [[1, 20], [3, 20], [4, 20]];
I want to combine these two into a new array:
var c = [[1, 10, 20], [2, 10], [3, 10, 20], [4, 10, 20], [5, 10]];
What's the best way to go about doing this. I'll update my question in a second with what I've tried to do.
var c = [];
for(var i = 0; i < a.length; i++) {
for(var j = 0; j < b.length; j++) {
if(a[i][0] == b[j][0]) {
// Push b value into a
a[i][0].push(b[j][1]);
} else {
// Don't do anything...
}
}
}
c = a; // Useless code here but just wanted to return c
return c;
Upvotes: 0
Views: 541
Reputation: 933
var a = [[1, 10], [2, 10], [3, 10], [4, 10], [5, 10]];
var b = [[1, 20], [3, 20], [4, 20]];
var c = [];
// Loop over a
for (var n = 0; n < a.length; n++) {
// Create copy of a's value
var subA = a[n].slice(0);
// Loop over b
for (var i = 0; i < b.length; i++) {
var subB = b[i];
// Check if a contains b
if (subA.indexOf(subB[0]) === 0) {
// Add b to new a value
subA.push(subB[1]);
}
}
// Add new value to c
c.push(subA);
}
console.log(a)
console.log(c);
Edit 1: updated for loop
Edit 2: If first item equals first item
Edit 3: Slice a to retain original values
Upvotes: 2
Reputation: 664346
Why don't you use plain arrays? They can be sparse.
var a = [10, 10, 10, 10, 10];
var b = [20, , 20, 20];
Now get them into one array:
var c = new Array(Math.max(a.length, b.length));
for (var i=0; i<c.length; i++)
if (i in a && i in b)
c[i] = [a[i], b[i]];
else if (i in a)
c[i] = [a[i]];
else if (i in b)
c[i] = [b[i]];
For the case that your objects (the items really don't have to be arrays) consist of a non-integer indexing values, you might use a simple standard merge algorithm on the two sorted lists. It will run in O(n+m)
, not in O(n*m)
as your solution. See this answer for an example implementation and further pointers.
Upvotes: 1