Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript reduce(),keys(), filter() method

While solving a problem to find missing numbers from an array.

let arr = [15,3,5,6,7,2,1,8,12];

let findMissing = (arr)=>{
    let res = arr.reduce((acc,n)=>{
        acc[n]=1;
        return acc;
    },[])
    
    return [...res.keys()].filter((i)=>{
        if(res[i]!==1) return i
    })
}

console.log(findMissing(arr));

output:[4, 9, 10, 11, 13, 14]

Issue is why output does not have zero in it: [0,4, 9, 10, 11, 13, 14]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

because you return i in the filter method (you return 0).
i === 0 && 0 == false it is filtered out because when returning a falsy value for a filter function it will strip it.

if you return true like in my example it works.

let arr = [15,3,5,6,7,2,1,8,12];

let findMissing = (arr)=>{
    let res = arr.reduce((acc,n)=>{
        acc[n]=1;
        return acc;
    },[])
    
    return [...res.keys()].filter((i)=>{
        return res[i] !== 1
    })
}

console.log(findMissing(arr));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading