Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

Conditionally join some of an array's items in JavaScript

发布于 2020-03-31 22:58:46

Let's say I have two arrays of same length:

const a = ['a', 'b', 'c', 'd'];
const b = [1, 1, 2, 1];

I want to join (.join('')) all consecutive items in a whose corresponding value in b (i.e. at the same index) are equal.

In this scenario, what I want to get is:

const result = ['ab', 'c', 'd']

Because a[0] and a[1] have the same corresponding value in b (i.e. b[0] === b[1]) and are consecutive in a, they are joined into the same string, forming a single item in result. However, although a[3]'s corresponding value in b is equal to a[0] and a[1]'s one, it's not joined to any of the latter as it isn't consecutive.

Questioner
Theo Avoyne
Viewed
15
Nina Scholz 2020-01-31 19:56

Just check if the value at b is the same at the given index and the sucessor.

const
    a = ['a', 'b', 'c', 'd'];
    b = [1, 1, 2, 1],
    result = a.reduce((r, v, i) => {
        if (b[i - 1] === b[i]) r[r.length - 1] += v;
        else r.push(v);
        return r;
    }, []);

console.log(result);