Sort an array alphabetically based on a search input

时间:2018-03-22 00:53:02

标签: javascript jquery arrays sorting

If I have an array such as:

["Adambb", "Andrebw", "Bob", "Billy", "Sandrab", "Xaviercb"]

And I type in a search box (for example) "B", how can I reorder the array in JavaScript with the results that match the string closest (also alphabetized), first?

For example, typing in "B" into the search box would reorder the array to:

["Billy", "Bob", "Adambb", "Andrebw", "Sandrab", "Xaviercb"]

I want the array to reorder much like any search system should work. For some reason I cannot find this answer anywhere online. Either I am not formulating my question right or I just can't find anything similar to my question.

4 个答案:

答案 0 :(得分:1)

另一种方法是检查字符串是否以输入的值开头,并对订单做出决定。

  • ab以输入的值开头时,进行字符串比较。
  • 如果a以输入的值开头且b没有,则将a放在开头。
  • 如果b以输入的值开头而不是,则请将b放在开头。
  • 否则,请进行默认字符串比较。



var array = [{id: "157", tag: "Adambb", course: "Adambb - Calculus I"}, {id: "158", tag: "Andrebw", course: "Andrebw - Ca I"}, {id: "159", tag: "Bob", course: "Bob - Cass I"}, {id: "160", tag: "Billy", course: "Billy - uus I"}, {id: "161", tag: "Sandrab", course: "Sandrab - allus I"}, {id: "162", tag: "Xaviercb", course: "Xaviercb - Cal I"}];

var input = 'Sa'; // Changed to illustrate the behavior.

var sorted = array.sort((a, b) => {
   if (a.course.startsWith(input) && b.course.startsWith(input)) return a.course.localeCompare(b.course);
   else if (a.course.startsWith(input)) return -1;
   else if (b.course.startsWith(input)) return 1;
     
   return a.course.localeCompare(b.course);;
});

console.log(sorted);

.as-console-wrapper { max-height: 100% !important; top: 0; }




另一种方法是检查字符串是否包含输入的值并对订单做出决定。

  • ab包含输入的值时,请进行字符串比较。
  • 如果a包含输入的值且b没有,则将a放在开头。
  • 如果b包含输入的值且a没有,则将b放在开头。
  • 否则,请进行默认字符串比较。



var array = [{id: "157", tag: "Adambb", course: "Adambb - Calculus I"}, {id: "158", tag: "Andrebw", course: "Andrebw - Ca I"}, {id: "159", tag: "Bob", course: "Bob - Cass I"}, {id: "160", tag: "Billy", course: "Billy - uus I"}, {id: "161", tag: "Sandrab", course: "Sandrab - allus I"}, {id: "162", tag: "Xaviercb", course: "Xaviercb - Cal I"}];

var input = 'r'; // Changed to illustrate the behavior.

var sorted = array.sort((a, b) => {
   if (a.course.indexOf(input) !== -1 && b.course.indexOf(input) !== -1) return a.course.localeCompare(b.course);
   else if (a.course.indexOf(input) !== -1) return -1;
   else if (b.course.indexOf(input) !== -1) return 1;
     
   return a.course.localeCompare(b.course);
});

console.log(sorted);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

假设你想在javascript中使用它。 您可以使用您可以作为参数传递给Array.sort方法的各种类型的compareFunction。

var compareFunction = function(a, b) {
  if (a.indexOf('B') < b.indexOf('B')) {
     return 1
  } else {
     return -1
  }
}
var arrToSort = ["Adambb", "Andrebw", "Bob", "Billy", "Sandrab", "Xaviercb"];
console.log(arrToSort.sort(compareFunction));

答案 2 :(得分:0)

这将帮助您入门。它获取第一个字符字符代码(ASCII),并按距离此代码排序。您将希望通过对字符串中的所有字符执行此操作来改进它,而不仅仅是第一个字符(第0个索引)。请记住,它没有考虑小写字母。您可以使用String.toLowerCase()来改善这一点。

&#13;
&#13;
let arr = ["Adambb", "Andrebw", "Bob", "Billy", "Sandrab", "Xaviercb"];
let arrCodes = arr.map(s=>({code:s.charCodeAt(0), value:s}));
let searchInput = document.getElementById("search-input");
searchInput.addEventListener("change", function(){
  let val = this.value;
  if(val){
    const code = val.charCodeAt(0);
    let sorted = arrCodes.sort(function(a, b){
      let distA = Math.abs(a.code-code);
      let distB = Math.abs(b.code-code);
      return distA-distB;
    });
    final = sorted.map(s=>s.value);
    console.log("sorted:", final);
  }
}, false);
&#13;
.as-console-wrapper {
  max-height: calc(100vh - 50px) !important;
}
&#13;
<input id="search-input" type="text" maxlength="1">
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是一个执行过滤排序的示例代码段。可能需要更多细化。此外,我没有考虑此解决方案中的外壳,因此区分大小写。

所以基本上在你的排序函数中你评估以下条件:

  1. x以过滤值开头但不是y;
  2. x不以过滤器值开头,但是y;
  3. x和y都以过滤值开头;因此,您希望在删除过滤器值后开始与字符串部分进行比较;
  4. x和y都不以过滤值开头;你想根据正常的排序保留他们的位置。
  5. <!DOCTYPE html>
    <html>
    <body>
    
    <input id="textFilter" type="text"/>
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    var names = ["Adambb", "Andrebw", "Bob", "Billy", "Sandrab", "Xaviercb"];
    document.getElementById("demo").innerHTML = names;
    
    function myFunction() {
    	var filterValue = document.getElementById("textFilter").value;
            
      // sort with a function
    	names.sort(function(x,y) {    	
            if( x.startsWith(filterValue) && !y.startsWith(filterValue))
            {
            	return -1;
            }
            else if (!x.startsWith(filterValue) && y.startsWith(filterValue))
            {
            	return 1;
            }
            else if(x.startsWith(filterValue) && y.startsWith(filterValue))
            {
            	var x2 = x.substring(filterValue.length-1);
              var y2 = y.substring(filterValue.length-1);
                
                return x2 > y2;
            }
            else
            {
            	return x > y;
            }
        });
        document.getElementById("demo").innerHTML = names;
    }
    </script>
    
    </body>
    </html>