简体   繁体   中英

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

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM