sevenfold
sevenfold

Reputation: 101

Searching elements of an array in JavaScript

I have two arrays, A = [22,33,22,33] and B = [3,10,5,9].

I want to create a new array like this C = [22,max(3,5), 33, max(10,9)]

Could someone help! Thanks in advance

Upvotes: 2

Views: 72

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386578

You could group by the values of array a and take the values of b at the same index of a for grouping.

var a = [22, 33, 22, 33],
    b = [3, 10, 5, 9],
    groups = new Map(),
    result;
    
a.forEach(g => groups.set(g, -Infinity)); // prevent zero false values
b.forEach((v, i) => groups.set(a[i], Math.max(groups.get(a[i]), v)));
result = [].concat(...groups);

console.log(result);

Upvotes: 3

Related Questions