WordPress search results grouped by post type

Solution found by counting! It counts if there are any posts and if not then skips.

<?php if ( have_posts() ) : ?>
    <?php
    $types = array('product' => 0, 'post' => 0, 'page' => 0);
    while ( have_posts() ) {
        the_post();
        if (array_key_exists(get_post_type(), $types)) {
            $types[get_post_type()]++;
        }
    }
    ?>
    <?php foreach ($types AS $type => $nb_of_type) : ?>
        <?php if ($nb_of_type > 0) : ?>
            <div class="post-type-wrap <?php echo $type; ?>">
                <div class="search-block-title"><h2><?php echo $blocktitle; ?></h2></div>
                
                    <?php while ( have_posts() ) : the_post(); ?>
                        <?php if ( get_post_type() === $type ) : ?>
                            <?php get_template_part('assets/search/content', $type); ?>
                        <?php endif; ?>
                    <?php endwhile; ?>                       

            </div>
        <?php endif; ?>
    <?php endforeach; ?>
    <?php else :
            _e( 'Sorry, no posts were found.' );
        ?>
<?php endif; ?>