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
Dathan
4,6134 gold badges27 silver badges46 bronze badges
-
2What’s the logic for picking those?Ry-– Ry- ♦2018年02月14日 07:52:08 +00:00Commented Feb 14, 2018 at 7:52
-
does both the arrays will be of same size always and you want to take maximum at those two specific points always?Anurag– Anurag2018年02月14日 07:52:28 +00:00Commented Feb 14, 2018 at 7:52
-
When findingequal elmnts in the array A go and search in the the array B the max corresponding to these elmtssevenfold– sevenfold2018年02月14日 07:53:57 +00:00Commented Feb 14, 2018 at 7:53
-
Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.caramba– caramba2018年02月14日 07:55:31 +00:00Commented Feb 14, 2018 at 7:55
-
Yes the same sizesevenfold– sevenfold2018年02月14日 07:55:53 +00:00Commented Feb 14, 2018 at 7:55
1 Answer 1
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);
answered Feb 14, 2018 at 7:58
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js