如何根据与单词的匹配程度对二维数组进行排序?

时间:2016-01-15 02:03:41

标签: javascript jquery arrays sorting

在这里小提琴:https://jsfiddle.net/t226j4ox/6/

我有一个2D数组,其中包含一个未排序的名称列表。

我试图弄清楚如何根据用户关键字的匹配程度对数组中的名称进行排序。在jsfiddle中,我将用户的关键字设置为" Be"用于测试目的。理想情况下,当您点击"排序名称"按钮,数组将被排序,以便以' Be'首先出现。

应该如何实现?

HTML

<div id="button1">
Display All Names
</div>

<br>

<div id="button2">
Sort Names
</div>

CSS

#button1{
  background:cornflowerblue;
  height:20px;
  width:200px;
  cursor:pointer;
  text-align:center;
}

#button2{
  background:mediumpurple;
  height:20px;
  width:200px;
  cursor:pointer;
  text-align:center;
}

JS

var nameList = "";

var names = [["name","Bradley"],["id","Brooke"],["name","Bobby"],
             ["name","Bethany"],["id","Benjamin"],["name","Bella"],
             ["name","Blake"],["id","Beatrice"],["name","Baby"],
             ["name","Byron"],["id","Buster"],["name","Bailey"],
             ["name","Betty"],["id","Billy"],["name","Brady"]];



var userKeyword = "Be";


$(document).on('click', '#button1', function(event) { 
        for (i=0; i<5; i++){
            nameList += names[i][1] + " ";        
        }

        alert(nameList);

}); 

$(document).on('click', '#button2', function(event) { 

}); 

1 个答案:

答案 0 :(得分:1)

使用sort功能

&#13;
&#13;
var nameList = '';

var names = [
	['name','Bradley'],
	['id','Brooke'],
	['name','Bobby'],
	['name','Bethany'],
	['id','Benjamin'],
	['name','Bella'],
	['name','Blake'],
	['id','Beatrice'],
	['name','Baby'],
	['name','Byron'],
	['id','Buster'],
	['name','Bailey'],
	['name','Betty'],
	['id','Billy'],
	['name','Brady']
];

var userKeyword = 'Be';

names.sort(function(a, b){
	return b[1].indexOf(userKeyword) - a[1].indexOf(userKeyword);
});


document.write(JSON.stringify(names));
&#13;
&#13;
&#13;