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
You can return multiple values from a function by wrapping them in an iterable. See this link on destructuring assignment.
Or
Array.forEach
do not return any value. You should use map instead :Note that
item
andindex
may be undefined if your condition is not fulfilled.To remove undefined you can chain map result with
Array.filter
: