javascript 合并两个数组,使值交替
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13253856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge Two Arrays so that the Values Alternate
提问by Undistraction
I'm looking for a jQuery method to merge two arrays so that their values alternate:
我正在寻找一种 jQuery 方法来合并两个数组,以便它们的值交替:
var array1 = [1,2,3,4,5];
var array2 = ['a', 'b', 'c', 'd', 'e'];
The result I want is:
我想要的结果是:
var arrayCombined = [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e'];
Please note that I know it is trivial to do this in JS, however I am after a jQuery method that will do this.
请注意,我知道在 JS 中执行此操作是微不足道的,但是我正在使用 jQuery 方法来执行此操作。
回答by Guffa
You can use the map
method:
您可以使用以下map
方法:
var array1 = [1, 2, 3, 4, 5];
var array2 = ['a', 'b', 'c', 'd', 'e'];
var arrayCombined = $.map(array1, function(v, i) {
return [v, array2[i]];
});
console.log(arrayCombined);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答by I Hate Lazy
If you mustuse jQuery, you can take advantage of their broken $.map
implementation.
如果您必须使用 jQuery,您可以利用其损坏的$.map
实现。
var result = $.map(array1, function(v, i) {
return [v, array2[i]];
});
jQuery's $.map
flattens the returned array, giving you the result you want.
jQuery$.map
会展平返回的数组,为您提供所需的结果。
DEMO:http://jsfiddle.net/8rn2w/
演示:http ://jsfiddle.net/8rn2w/
Pure JS solution:
纯JS解决方案:
var result = array1.reduce(function(arr, v, i) {
return arr.concat(v, array2[i]);
}, []);
回答by Rahul Tripathi
Try something like this:-
尝试这样的事情:-
function merge(array1, array2) {
if (array1.length == array2.length) {
var c = [];
for (var i = 0; i < array1.length; i++) {
c.push([array1[i], array2[i]]);
}
return c;
}
return null;
}
}
回答by Sanchit Kumar
Just another solution using Array.prototype.flat()and Array.prototype.map().
使用Array.prototype.flat()和Array.prototype.map() 的另一种解决方案。
var array1 = [1, 2, 3, 4, 5];
var array2 = ['a', 'b', 'c', 'd', 'e'];
var result = array1.map(
(element, index) => [element, array2[index]]
).flat();
回答by VLAZ
Using ES6 generator functionsthis can be implemented generically for any amount of arrays of any lengths. The key is going through all arrays regardless of length in order and then adding each of the values they have into a single merged array. By using the iterator protocolof arrays we can uniformly proceed through the items in each array.
使用 ES6生成器函数,这可以针对任意数量的任意长度的数组进行通用实现。关键是按顺序遍历所有数组,而不管长度如何,然后将它们拥有的每个值添加到一个合并的数组中。通过使用数组的迭代器协议,我们可以统一处理每个数组中的项目。
//go through all arrays and produce their values
function* parallelWalkAllArrays(...arrays) {
//get iterator for each array
const iterators = arrays.map(arr => arr[Symbol.iterator]());
let values;
//loop until complete
while (true) {
values = iterators
.map(it => it.next()) //addvance iterators
.filter(({done}) => !done) //keep anything that is not finished
.map(({value}) => value); //get the values
//quit if all are exhausted
if (values.length === 0)
return;
//yield a tuple of all values
yield values;
}
}
function interleaveMergeArrays(...arrays) {
//start a generator function
const sequence = parallelWalkAllArrays(...arrays);
let merged = [];
//flatten each result into a single array
for (const result of sequence) {
merged.push(...result)
}
return merged;
}
const array1 = [1,2,3,4,5];
const array2 = ['a', 'b', 'c', 'd', 'e'];
console.log(
interleaveMergeArrays(array1, array2)
);
const shortArray = ["apple", "banana"];
console.log(
interleaveMergeArrays(array1, shortArray)
);
console.log(
interleaveMergeArrays(shortArray, array2)
);
console.log(
interleaveMergeArrays(array1, shortArray, array2)
);
Alternatively, you can take a very similar approach but directly produce a flat sequence from the generator. That way you can consume it immediately.
或者,您可以采用非常相似的方法,但直接从生成器生成平面序列。这样您就可以立即食用它。
//go through all arrays and produce their values
function* walkAllArrays(...arrays) {
//get iterator for each array
const iterators = arrays.map(arr => arr[Symbol.iterator]());
let values;
//loop until complete
while (true) {
values = iterators
.map(it => it.next()) //addvance iterators
.filter(({done}) => !done) //keep anything that is not finished
.map(({value}) => value); //get the values
//quit if all are exhausted
if (values.length === 0)
return;
//yield each value
for (const value of values)
yield value;
}
}
const array1 = [1, 2, 3, 4, 5];
const array2 = ['a', 'b', 'c', 'd', 'e'];
console.log(Array.from(
walkAllArrays(array1, array2)
));
const shortArray = ["apple", "banana"];
console.log(Array.from(
walkAllArrays(array1, shortArray)
));
console.log(Array.from(
walkAllArrays(shortArray, array2)
));
console.log(Array.from(
walkAllArrays(array1, shortArray, array2)
));
I personally find the latter approach less flexible, as it only solves this problem. Doing a parallel sequential walk through all arrays can be re-used for other things such as zipping arrays, so having a helper function consume the output of that seems like it can leave more options open. On the other hand having a single function makes it a bit more straightforward to see how it's implemented.
我个人认为后一种方法不太灵活,因为它只能解决这个问题。对所有数组进行并行顺序遍历可以重新用于其他事情,例如压缩数组,因此使用辅助函数消耗输出似乎可以留下更多选项。另一方面,只有一个函数可以更直接地了解它是如何实现的。