Reputation: 659
I have an assignment that sounds like:
Computer put two arrays with random strings in Test.data. Need a single list which contains one element from a, then one from b, and so forth.
Example:
a: ['a', 'b', 'c']
b: ['d', 'e']
-> ['a', 'd', 'b', 'e', 'c']
I tried this code, but it simply replaces the data that is in the Test.data.
Test.data = function arry(a, b) {
const c = [];
for (let i = 0; i < Math.max(a.length, b.length); i++) {
if (a[i] != undefined) {
c.push(a[i]);
}
if (b[i] != undefined) {
c.push(b[i]);
}
}
}
The mistake is how I apply the function to the object, but I do not know how to solve it
Upvotes: 0
Views: 76
Reputation: 3048
I've tried to clean up your code, hopefully it helps
var a = ['a', 'b', 'c'],
b = ['d', 'e'];
function Test(a, b)
{
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++)
{
if (a[i] !== undefined)
{
c.push(a[i]);
}
if (b[i] !== undefined)
{
c.push(b[i]);
}
}
console.log(c);
}
Test(a, b);
Upvotes: 1
Reputation: 947
I think this is what you're trying to do?
function arry(a, b) {
const c = [];
for (let i = 0; i < Math.max(a.length, b.length); i++) {
if (a[i] != undefined) {
c.push(a[i]);
}
if (b[i] != undefined) {
c.push(b[i]);
}
}
return c;
}
let alpha = ['a', 'b', 'c'];
let beta = ['d', 'e'];
Test.data = arry(alpha, beta)
Upvotes: 3