skip to Main Content

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]

2

Answers


  1. 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));
    Login or Signup to reply.
  2. Alternatively, findMissing() can be written as a one-liner, using .reduce() and .includes():

    let arr = [15,3,5,6,7,2,1,8,12];
    
    let findMissing=arr=>
      Array(Math.max(...arr)+1).fill(0)
      .reduce((a,_,i)=>(!arr.includes(i)&&a.push(i),a),[]);
    
    console.log(findMissing(arr));

    However, the performance could be improved by creating a Set s from arr with s=new Set(arr) and then using !s.has(i) instead of !arr.includes(i) inside the reduce() callback function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search