简体   繁体   English

Javascript数组:优先合并2个数组

[英]Javascript arrays: merge 2 arrays with priority

How to merge two arrays of different lengths and the values of the shorter array should have priority over the larger array's values, but the result should still have the length of the larger array. 如何合并两个不同长度的数组以及较短数组的值应该优先于较大数组的值,但是结果仍应具有较大数组的长度。 Please look closely how I arranged the two arrays below: 请仔细查看我如何排列以下两个数组:

var short  = [[ 25,12],          [576, 12],          [576,584],          [ 25,584],          [ 25,12]];
var long   = [[301,12],[400,192],[602,230],[461,380],[487,584],[301,497],[115,584],[140,380],[301,12]];
// --------------------as suggested by the above
var result = [[ 25,12],[400,192],[576, 12],[461,380],[576,584],[301,497],[ 25,584],[140,380],[ 25,12]];

In the example above it seems the length of long is twice compared to short , but it should work even if it's triple in size or just one element longer. 在上面的示例中, long的长度似乎是short两倍,但是即使它的大小是原来的三倍或只是一个元素长,它也应该起作用。

This is quite straightforward. 这很简单。 Simply create a copy of the longer array, then overwrite elements in this copy with elements from the shorter array. 只需创建较长数组的副本,然后用较短数组中的元素覆盖此副本中的元素。

var m = Math.floor(long.length/short.length);

var result = long.slice();
for(var i = 0; i < short.length; ++i) {
    result[i*m] = short[i];
}

Later edit : Actually, this is wrong. 以后编辑 :实际上,这是错误的。 The interesting problem in this question is the spacing algorithm, and you cannot get that by this particular simple multiplication. 这个问题中有趣的问题是间距算法,您不能通过这种特殊的简单乘法来获得间距算法。

I'll leave this answer here anyway, because it might help clarify what this problem is. 无论如何,我都会在这里留下这个答案,因为这可能有助于弄清这个问题是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM