简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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