Overview
Implement unionBy(iteratee, ...arrays) — returns a combined array with uniqueness determined by iteratee.
Examples
unionBy(Math.floor, [2.1, 1.2], [2.3, 3.4]); // [2.1, 1.2, 3.4]
Solution
Reveal solution
function unionBy(iteratee, ...arrays) {
const seen = new Set();
const result = [];
for (const arr of arrays) {
for (const item of arr) {
const key = iteratee(item);
if (!seen.has(key)) { seen.add(key); result.push(item); }
}
}
return result;
}union-by.js
Union By
mediumcodingJavaScriptArrays
Overview
Implement unionBy(iteratee, ...arrays) — returns a combined array with uniqueness determined by iteratee.
Examples
unionBy(Math.floor, [2.1, 1.2], [2.3, 3.4]); // [2.1, 1.2, 3.4]
Solution
Reveal solution
function unionBy(iteratee, ...arrays) {
const seen = new Set();
const result = [];
for (const arr of arrays) {
for (const item of arr) {
const key = iteratee(item);
if (!seen.has(key)) { seen.add(key); result.push(item); }
}
}
return result;
}NameTopicDifficulty
103 of 103 problems