Ad

How To Sort Twodimensional Array By How Closely It Matches A Word?

- 1 answer

Fiddle here: https://jsfiddle.net/t226j4ox/6/

I have a 2D array which contains an unsorted list of names.

I'm trying to figure out how to sort the names in the array by how closely they match the user's keyword. In the jsfiddle, I set to user's keyword to "Be" for testing purposes. Ideally, when you hit the "Sort Names" button, the array would be sorted so that names starting with 'Be' appear first.

How should this be achieved?

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 = "BBilly"],["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) { 

}); 
Ad

Answer

Use sort function

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));

Ad
source: stackoverflow.com
Ad