How about the most obvious approach for the first case, which should make use of filter, since the author’s implementations both actually do not remove odd numbers, but do both filter even numbers from the source array, thus …
console.log(
[4, 1, 9, 10, 15, 22, 5, 14].filter(value => !(value % 2))
);
… or even more readable / user friendly …
const isEven = value => !(value % 2);
const isOdd = value => !!(value % 2);
console.log(
[4, 1, 9, 10, 15, 22, 5, 14].filter(isEven)
);
console.log(
[4, 1, 9, 10, 15, 22, 5, 14].filter(isOdd)
);
The second example already fails with its title which is “2. Find all repeated numbers from an array”, but does not implement what it says. The algorithm instead creates an array of unique values which is an entirely different task than finding all repeated numbers. For the latter the result has to be [1] since 1 is the only value which occurres more than once.
And the approach itself introduces an quadratic effort due to nesting a filter task within a map task. And the usage of map is a real big failure, because nothing gets mapped (the mapping callback neither does return a meaningful value, nor is there any usage of the returned mapped array). The author should have used forEach instead.
The uniqueness of simple values within an array gets best achieved via a Set instance and immediately spreading it back into an array …
console.log(
[...new Set([1,2,4,5,6,1,3,7,9,10])]
);
… and an approach which prevents quadratic complexity should be based on any variation of looking-up already processed values. A solution which actually does cover the topic of … “Find all repeated numbers from an array” and also achieves a close to linear complexity, might make use of reduce and a Map instance, and could look similar too …
function collectRepeatadlyOccuringValueOnly(
{ result = [], lookup = new Map }, value
) {
const occurrenceCount = lookup.get(value) ?? 0;
if (occurrenceCount === 1) {
result.push(value);
}
lookup.set(value, occurrenceCount + 1);
return { result, lookup };
}
console.log(
[1, 2, 4, 5, 6, 1, 3, 7, 9, 10]
.reduce(collectRepeatadlyOccuringValueOnly, { result: [] })
.result
);
console.log(
[1, 2, 4, 5, 10, 6, 1, 3, 10, 7, 6, 9, 10]
.reduce(collectRepeatadlyOccuringValueOnly, { result: [] })
.result
);
I’m going to stop here, but every reader should be aware that everything which follows after the author’s second example most probably is of equally poor quality as the former two.