Overview
Implement flatMap(array, callback) that maps each element through callback and flattens one level.
Examples
flatMap([1,2,3], x => [x, x * 2]); // [1,2,2,4,3,6] flatMap([[1],[2]], x => x); // [1,2]
Solution
Reveal solution
function flatMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
const val = callback(array[i], i, array);
if (Array.isArray(val)) result.push(...val);
else result.push(val);
}
return result;
}array-prototype-flat-map.js
Array.prototype.flatMap
easycodingJavaScriptArrays
Overview
Implement flatMap(array, callback) that maps each element through callback and flattens one level.
Examples
flatMap([1,2,3], x => [x, x * 2]); // [1,2,2,4,3,6] flatMap([[1],[2]], x => x); // [1,2]
Solution
Reveal solution
function flatMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
const val = callback(array[i], i, array);
if (Array.isArray(val)) result.push(...val);
else result.push(val);
}
return result;
}NameTopicDifficulty
103 of 103 problems