Home > Software engineering >  Simplifying an Array containing an array of objects
Simplifying an Array containing an array of objects

Time:10-18

I have this array of customer licenses I am sorting through and creating a live search function with an array that updates properly. The issue I am facing is that I want my filtered array to be an array like this [[{},{},{},{},{}]] currently after typing in a word to filter the array looks like this instead [ [{}], [{},{}], [{},{}] ] or something similar whereas its an array with multiple arrays instead of just one.

I'm sure its something simple that I have overlooked in the past couple of hours trying to figure out how to achieve what I want.

function FilterResults(term, results)
{
    return results.reduce((filtered, group) => 
    {
        const match = group.filter(({ customerName }) => customerName.toLowerCase().includes(term.toLowerCase()));
            
        match.length && filtered.push(match);
        
        return filtered;
    }, []);
}

CodePudding user response:

I am not sure if you really want an array inside of another array but You can do it like this one. I have spread and then pushed the match array and returned the result in a new array.

  function FilterResults(term, results)
{
    const res = results.reduce((filtered, group) => 
    {
        const match = group.filter(({ customerName }) => customerName.toLowerCase().includes(term.toLowerCase()));
            
    match.length && filtered.push(...match);
    
    return filtered;
}, []);

return [res]
}
  • Related