-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
terceiro capítulo #3
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That works! However, we can simplify it a lot by using the power of Sets in JS:
let arrDuplicados = [1, 2, 3, 2, 1, 4, 5];
let set = new Set(arrDuplicados)
console.log("Array sem duplicados:", [...set]);
A Set is a list of unique values, when we initialize a set with an array, it automatically removes the duplicated values to create the Set. After that, we can just turn the Set back into an Array with the help of the spread operator (...
).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Dammn, much easier 🤯
function contarOcorrencias(arr, num) { | ||
let i = 0 | ||
for (item of arr) { | ||
if (num == item) | ||
i++ | ||
}return i | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct :)
A one line solution using reduce
could be:
function contarOcorrencias(arr, num) {
return arr.reduce((acc, curr) => curr === num ? acc + 1 : acc, 0)
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also correct!
We could also use reduce
for this one like so:
function somarPares(arr) {
return arr.reduce((acc, curr) => curr % 2 === 0 ? acc + curr : acc, 0)
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can also use the power of JavaScript sets for this one 👀
function contarDiferentes(s) {
const set = new Set(s.split(""))
return [...set].length
}
No description provided.