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

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

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

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

Синтаксис:

_.sortedIndex(array, value, [iteratee], [context])

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

  • Массив
  • Значение
  • Итерируемый (необязательно)

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

Примеры:

  1. Passing a list of numbers to _.sortedIndex() function:
    The ._sorted() function takes the element from the list one by one and checks whether the element is less than the new element or not. If it is less, then it is ignored and the _.sortedIndex() checks the same on the next element from the list. Otherwise if the element is greater then this function returns the index of this element. This means that the new element should come at this index and the elements from this index on wards first need to shift one step behind so as to make space for the new element.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.sortedIndex([1, 2, 4, 5, 6], 3));
        </script>
    </body>
       
    </html>

    Output:

  2. Passing another number list to the _.sortedIndex() function:
    We can pass any length of the array to the _.sortedIndex() function. It will perform a binary search to find the place of the new element. In binary search all the elements which are in the array are compared to the new element so as to find it’s new index. Finally, console.log() the new index found.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.sortedIndex([1, 2, 3, 4, 5, 6, 8], 7));
        </script>
    </body>
       
    </html>

    Output:

  3. Passing a structure to the _.sortedIndex() function:
    We can even pass a structure containing more than one key for property. In this we need to mention on the basis of which key we want to perform the binary search. Like in the below example we have 2 keys, which are name and the sal. And later we have passed the sal property as the comparison parameter after mentioning the element which we need to insert.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.sortedIndex([{name: "amit", sal: 40000},
                                       {name: "ankit", sal: 60000}, 
                                       {name: "anju", sal: 80000}], 
                                       {name: "akash", sal: 70000}, 
                                                           "sal"));
        </script>
    </body>
       
    </html>

    Output:

  4. Applying the search on a character:
    We can even perform the binary search on the characters rather than on the numbers. In this we pass a structure with 3 properties, name, rollNo and the section. In this we pass the third property for the comparison which contains the characters. The result will be in the similar way with no errors.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.sortedIndex([{name: "akansha", rollNo: 01, section:"a"},
                                       {name: "aishwarya", rollNo:02, section:"b"},
                                       {name: "anjali", rollNo:03, section:"d"}],
                                       {name: "preeti", rollNo:04, section:"c"}, 
                                                                      "section"));
        </script>
    </body>
       
    </html>

    Output:

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

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