Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching JavaScript array elements after consecutive occurrence of an element

I have a JavaScript array like:

var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];

I want to fetch only those elements of the array that come after 2 consequent occurrences of a particular element.

i.e. in the above array, I want to fetch all the elements that come after consequent 'x', 'x'

So my output should be:

'p'
'b'

I have a solution like :

var arrLength = myArray.length;
for (var i = 0; i < arrLength; i++) {
    if(i+2 < arrLength && myArray[i] == 'x' && myArray[i+1] == 'x') {
        console.log(myArray[i+2]);
    }
};

This satisfies my needs, but it is not so generic.

For eg. if I have to check for 3 consequent occurrences, then again I have to add a condition inside if for myArray[i+2] == 'x' and so on.

Could anyone provide a better way to fetch the elements?

like image 241
Chittaranjan Sahoo Avatar asked Jan 16 '16 19:01

Chittaranjan Sahoo


2 Answers

The functional way would be to use recursion. With an ES6 spread, you can pretty much emulate the terseness of a truly 'functional' language :-)

var myArray = ['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'];

function reducer(acc, xs) {
    if (xs.length > 2) {
        if (xs[0] === xs[1]) {
            // add the third element to accumulator
            // remove first three elements from xs
            // return reducer([xs[2], ...acc], xs.slice(3));
            // or per Nina's question below
            return reducer([xs[2], ...acc], xs.slice(1));
        } else {
            // remove first element from xs and recurse
            return reducer(acc, xs.slice(1))
        }
    } else {
        return acc;
    }
}

console.log(reducer([], myArray));
like image 51
Simon H Avatar answered Nov 17 '22 13:11

Simon H


A generic straight forward approach for any comparable content.

function getParts(array, pattern) {
    return array.reduce(function (r, a, i) {
        i >= pattern.length && pattern.every(function (b, j) {
            return b === array[i + j - pattern.length];
        }) && r.push(a);
        return r;
    }, []);
}

function p(o) {
    document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}

p(getParts(['a', 'x', 'x', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'], ['x', 'x']));
p(getParts(['a', 'x', 'b', 'x', 'x', 'p', 'y', 'x', 'x', 'b', 'x', 'x'], ['a', 'x', 'b']));
p(getParts(['a', 'b', 'c', 'd', 'z', 'y', 'a', 'b', 'c', 'd', 'x', 'x'], ['a', 'b', 'c', 'd']));
p(getParts([41, 23, 3, 7, 8, 11, 56, 33, 7, 8, 11, 2, 5], [7, 8, 11]));
like image 3
Nina Scholz Avatar answered Nov 17 '22 14:11

Nina Scholz