Skip to content
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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

terceiro capítulo #3

wants to merge 3 commits into from

Conversation

gxnca
Copy link

@gxnca gxnca commented Nov 19, 2024

No description provided.

@gxnca gxnca requested review from nunom27 and diogogmatos November 19, 2024 23:54
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

Copy link
Member

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 (...).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dammn, much easier 🤯

Comment on lines +3 to +9
function contarOcorrencias(arr, num) {
let i = 0
for (item of arr) {
if (num == item)
i++
}return i
}
Copy link
Member

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)
}

Copy link
Member

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)
}

Copy link
Member

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants