skip to Main Content

I want to find an item and the index of this item inside array and store this in 2 separate variables. Quite new to programming but struggling to solve the problem. I tried destructing but it is not working

    const [{item:item,index:index}] = notification.pendingQueue.forEach((item,index)=>
         {
             if(item.taskId.toString()  === req.params.taskId)
             return [{item, index}];
         }) 
         

Tried this as well

const data = notification.pendingQueue.forEach((item,index)=>
         {
             if(item.taskId.toString()  === req.params.taskId)
             return ({'item': item,  'index': index})
         }) 
         

         console.log("item", data.item );


I’m getting this error

undefined is not iterable (cannot read property Symbol(Symbol.iterator)) TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

—— Edit ————-

As suggested by the community member, I tried .map method but now the issue is I get results like this if the 2nd element matches the condition.

[undefined, {item,index}, undefined] 

so doing object destructing is becoming a problem. I want the final array to contain just the matching object and remove all undefined values.

const [{ item, index }] = notification.pendingQueue.map((item,index)=>
         {
             if(item.taskId.toString()  === req.params.taskId)
             return { item, index };
         }) ;

2

Answers


  1. You can return multiple values from a function by wrapping them in an iterable. See this link on destructuring assignment.

    function coordinates (country = null) {
       if (!country) return [-1, -1];
       // ...
       let lat = "19.9823";
       let lon = "0.9039";
       return [lat, lon];
    }
    
    const [a, b] = coordinates("London, UK");
    

    Or

    function coordinates (country = null) {
       if (!country) return {-1, -1};
       // ...
       let lat = "19.9823";
       let lon = "0.9039";
       return {lat, lon};
    }
    const {lat, lon} = coordinates("Tokyo, JP");
    
    Login or Signup to reply.
  2. Array.forEach do not return any value. You should use map instead :

    const [{ item, index }] = notification.pendingQueue.map((item,index)=>
             {
                 if(item.taskId.toString()  === req.params.taskId)
                 return { item, index };
             }) ;
    
    

    Note that item and index may be undefined if your condition is not fulfilled.

    To remove undefined you can chain map result with Array.filter :

    const [{ item, index }] = notification.pendingQueue.map((item,index)=>
             {
                 if(item.taskId.toString()  === req.params.taskId)
                 return { item, index };
             }).filter(elem => elem !== undefined) ;
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search