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

Lecture 6 - JavaScript Array and Object Deep Dive (Time: 2:03:56) #56

Open
Murad-Hasan opened this issue Jan 7, 2023 · 2 comments
Open

Comments

@Murad-Hasan
Copy link
Contributor

In this lecture, Nayem vai with an array like
const number = [1,2,3,4,NaN,false,'',5,7,8]
For converting an array to a truthy string and making a custom array with string concatenation like
[ 1, 2, 3, 4, 5, 7, 8 ]
The following code is

const truthyValue = number.reduce((acc,cur, index) => {
    if (index === 0) acc += '[ '
    if (cur){
        acc += cur.toString() + (`${index < number.length - 1 ? ', ' : ''}`)
    }
    if (index === number.length - 1 ) acc+=' ]'
    return acc;
}, '')

But when I am going to use another array-like

const number = [1,2,3,4,NaN,false,'']

For this, why is the code not working?
Maybe, One reason is that the array doesn't end with a number.
Have anyone any idea about this?

@MOHAMMADmiZAN
Copy link

const number = [1,2,3,4,NaN,false,''];
const truthyValue = number.reduce((acc,cur, index) => {
if (index === 0) acc += '[ ';
if (cur){
acc += cur.toString() + (${index < number.length - 1 ? ', ' : ''});
}
if (cur && !number.slice(index+1).some(Boolean)) acc+=' ]';
return acc;
}, '');

console.log(truthyValue); // Output: [ 1, 2, 3, 4 ]

@nuruddin-bin-hoda
Copy link

Try this algorithm

const arr = [1, 2, 3, 4, NaN, false, ""];

let i, j = 0;
for (i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number" && !isNaN(arr[i])) {
arr[j++] = arr[i];
}
}
arr.length -= i - j;

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

No branches or pull requests

3 participants