javascript - How to elegantly alternate iterate over two arrays?
phpcn_u1582
phpcn_u1582 2017-05-19 10:41:15
0
2
657

Restricted language: Javascript

For example, several activity pits will be inserted into a product list.

For example, there are two arrays A and B with variable lengths. It requires 6 A array elements and 1 B array element to be arranged like this

For example, even more arrays are arranged alternately

What I can think of is to convert these arrays into two-dimensional arrays like paging, then use a loop to combine them into an array, and finally traverse.

Is there a better way

phpcn_u1582
phpcn_u1582

reply all(2)
phpcn_u1582
var a = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5],
    b = [11,22,33,44,55];
    
a.reduce((acc,ele,idx) => ((idx + 1) % 3 ? acc.push(ele) : acc.push(ele, b.shift()), acc), []);

How elegant? . .

巴扎黑
export function join<T>(first: T[], second: T[], firstSize: number, secondSize: number): T[] {
    let out: T[] = []
    let i = 0
    for (; firstSize * i < first.length && secondSize * i < second.length; i++) {
        out = out.concat(
            first.slice(firstSize * i, firstSize),
            second.slice(secondSize * i, secondSize),
        )
    }
    out = out.concat(first.slice(firstSize * i), second.slice(secondSize * i))
    return out
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template