Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Javascript search and sort array elements

List: Change block type or style Convert to unordered list Convert to ordered list Outdent list item Indent list item ▲ ▲ Add title Javascript search and sort array elements

Let’s demonstrate Javascript search and sort array elements. In this example, search match input, if it found a match then add match search query at the beginning and add remaining sort after it.

Example of Javascript search and sort array elements

Here is a screenshot of our Javascript search string in the array.

Javascript search and sort array elements
Javascript search and sort array elements

Let first add our word list in a Javascript file search-words.js

function getSearchWords() {
    return [
        'angular',
        'php',
        'pull',
        'push',
        'ionic',
        'javascript',
        'node',
        'angularjs',
        'note'
    ];
}

Add the following code in search-list.html, we have the following actions.

  1. An input box to add a search query
  2. A button, to call search query.

When a button is clicked, it first searches the query in our words array in search-words.js, and if it is found a match. Then we can split the data into two arrays, one that starts with match query input and the other with not match string. Sort each separately, then combine the two results:

<!DOCTYPE HTML>
<html>

<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <style>
    div.search-result {
      padding: 5px;
      width: 850px;
      /* color: #fff;
      background-color: #1100ff; */
      border: 1px solid #1b0fc0;
      border-radius: 5px;
    }
  </style>
</head>

<body>
  <div class="container mt-4">
    <div class="search-result">
      <div>
        <strong>Original String:</strong>
        <span id="org-array"></span>
      </div>
      <br /><br />

      <div class="form-group">
        <label for="search-query">Search word in above array string and add it at beganing and sort the
          remaining</label>
        <input class="form-control" placeholder="add search word" id="search-query">
      </div>

      <div class="d-md-flex justify-content-md-end mt-2 mb-2">
        <button type="submit" id="search-button" class="btn btn-primary">Search & sort</button>
      </div>


      <div>
        <strong>Search and sort string :</strong>
        <span id="sort-array"></span>
      </div>
      <script src="search-words.js"></script>
    </div>


    <script>
      function sortInputMatch(input, data) {
        const first = [];
        const others = [];

        for (let i = 0; i < data.length; i++) {
          if (data[i].indexOf(input) == 0) {
            first.push(data[i]);
          } else {
            others.push(data[i]);
          }
        }
        first.sort();
        others.sort();
        return (first.concat(others));
      }

      document.getElementById('org-array').innerHTML = '[' + getSearchWords() + ']';

      const button = document.getElementById('search-button');

      button.addEventListener('click', ev => {
        const query = document.getElementById('search-query').value;
        if (query) {
          const searchSortArray = sortInputMatch(query, getSearchWords());
          document.getElementById('sort-array').innerHTML = '[' + searchSortArray + ']';
        } else {
          alert('Search query not found in string list');
        }
      });
    </script>
</body>
</html>

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending.

The contact() method combine two or more arrays.

Related Post

Javascript search and sort array elements

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top