Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

jquery - Finding matches amongst multiple javascript arrays and output the repeating array

I just want to find matches between multiple arrays based on first value in an array and keep the matching results.

[
    [[11,1], [22,2], [33,3]],
    [[11,1], [10,1], [22,1]],
    [[11,10], [12,1], [22,1]]
]

Above is my sample array. first unique values in those arrays are 11, 22, 33, 10, 12 so out of which 11, 22 are repeated across all the three arrays.

And would like to to produce the following array that contains matches from all given arrays:

[
    [[11,1], [22,2]],
    [[11,1], [22,1]],
    [[11,10], [22,1]]
]

I just tried with javascript reduce function, but couldn't solve it and not getting the result as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could filter first for common values and map the result with the filtered arrays.

const
    data = [
        [[11, 1], [22, 2], [33, 3]],
        [[11, 1], [10, 1], [22, 1]],
        [[11, 10], [12, 1], [22, 1]]
    ],
    common = data.reduce((a, b) => a.filter(([v]) => b.some(([w]) => v === w))),
    result = data.map(a => a.filter(([v]) => common.some(([w]) => v === w)));

console.log(common);
console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...