Функция Underscore.js _.chunk()

Опубликовано: 7 Октября, 2022

Функция _.chunk():

  • Он используется для разделения переданного массива на несколько массивов, содержащих количество элементов, указанное во втором параметре функции _.chunk().
  • С помощью этой функции мы можем преобразовать один массив в несколько массивов.
  • Также во втором параметре должно быть указано количество элементов, которые будет содержать результирующий массив.

Синтаксис:

_.chunk(array, length) 

Параметры:
Он принимает два аргумента:

  • Массив
  • Длина результирующих массивов

Возвращаемое значение:
Возвращает количество массивов, которые образовались после разбиения.

Примеры:

  • Passing a list of numbers to _.chunk() function:
    The _.chunk() function takes the element from the list one by one and forms an array until the number of elements in the resultant array is equal to the given number in the second parameter. Then, if the elements in the given array are still present then it forms another array in the result. Finally, the total number of arrays formed is equal to the number of elements in the passed array divided by the number given in the second element.
     




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.chunk([1, 2, 3, 4, 5, 6], 2));
        </script>
    </body>
       
    </html>

    Output:

  • Passing a larger array size to the _.chunk() function:
    If we pass a larger sized number in the second parameter then also it works in the same way. Like here the number of elements is given is 3. So, we form the number of arrays. Each array has three elements in the same order it is present in the passed array.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.chunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3));
        </script>
    </body>
       
    </html>

    Output:

  • Passing a list of characters to the _.chunk() function:
    Even if we pass the array containing alphabets .i.e., string of characters rather than numbers then also it will work in the same manner. This implies that the _.chunk() function does not distinguish between numbers, characters, etc. Also, since here the number passed in the second parameter is a two but the passed array has five elements. Therefore, the last element will have only one element. It will not give any error.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(
    _.chunk(["HTML", "CSS", "JS", "AJAX", "PEARL"], 2));
        </script>
    </body>
       
    </html>

    Output:

  • Having the same number of the array as the number of elements to the _.chunk() function:
    We can even obtain the result the same number as the elements passed in the array. This makes the use of _.chunk() function more convenient. For this, we just need to pass the second parameter as 1. This implies that the size of each array will be one.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(
    _.chunk(["HTML", "CSS", "JS", "AJAX", "PEARL"], 1));
        </script>
    </body>
       
    </html>
    </html>

    Output:

ПРИМЕЧАНИЕ:
Эти команды не будут работать в консоли Google или в Firefox, так как необходимо добавить эти дополнительные файлы, которых они не добавили. Итак, добавьте указанные ссылки в свой HTML-файл, а затем запустите их. Ссылки следующие:

Пример показан ниже: