0

i'm tryin' to explain what i want. I have two arrays:

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
my_array_two = ["string", "string", "string", "string", "string", "string", "string", "string", "string", "string" ];

and i need to merge this arrays but in a specific way. The new array will be:

my_new_array = [1, 2, "string", 3, 4, "string", 5, "string", 6, "string", 7, "string", 8, "string", 9, "string", 10, "string", "string", "string" ]

The arrays length can be from 1 to 10. I can't figure out how can i do this, i hope some help for this task. Thanks in advance

4

3 回答 3

0

不确定具体的模式是什么,但就基本算法而言,我会推荐这样的东西:

var combined_array = [];
var index1 = 0, index2 = 0;
while ((index1 < my_array.length) && (index2 < my_array_two.length)) {
    if (/*you're at the end of either array*/) {
        // take the next element from the other one.
    }
    else {
        if (compare(my_array[index1], my_array_two[index2])) {
            combined_array.push(my_array[index1]);
            ++index1;
        }
        else {
            combined_array.push(my_array_two[index2]);
            ++index2;
        }
    }
}

如果第一个值应该在第二个之前,您编写的某个函数在哪里compare看起来两个值并返回 true。

于 2013-10-30T21:46:27.967 回答
0

如果这是一个原始算法,那么最好的办法就是编写自己的排序算法来合并两者。

于 2013-10-30T21:33:04.027 回答
0

我可以从显示的特定输入和输出中推断出的唯一模式是从第一个数组中获取两个值,然后从第二个数组中获取一个值,然后从第一个数组中获取两个值,然后从每个数组中交替获取一个值,直到两个数组中的所有值都被使用数组。

如果这是正确的,那么以下代码将执行此操作:

// copy first input array into output array
var my_new_array = my_array.slice(0);    
// loop over second array
for (var i = 0, j = 2; i < my_array_two.length; i++){
    // insert next item into output at position j
    my_new_array.splice(j, 0, my_array_two[i]);
    // figure out next position to insert    
    j += (j < 4) ? 3 : 2;
}
于 2013-10-30T21:34:42.770 回答