JSFiddle - React, Tailwind, and code Playground
HTML
<p class="help">Enter [type] [space] [value] for each tip in a new line.</p>
<textarea id="input">
3 4
2 4
1 3
4 10</textarea>
<button id="process">Process Input and Sort</button>
<hr />
<h2>Sorted Tips</h2>
<div id="results"></div>
CSS
body {
font-family: Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif;
}
p.help {
color: #444;
}
textarea {
padding: 5px;
font-size: 0.9em;
width: 20%;
height: 80px;
}
p, textarea, button {
margin: 5px 0;
}
button {
display: block;
}
#results {
background-color: #EEE;
}
JavaScript
function Tip(type, value) {
this.type = type;
this.value = value;
}
function process(tips) {
tips.sort(function(a, b) {
// sort first by value, and if equal, then by type (index)
return (b.value - a.value) || (a.type - b.type);
});
// Show sort results on page
var container = $('results').empty();
tips.each(function(tip) {
var str = "{index} => {value}".substitute({
index: tip.type,
value: tip.value
});
container.grab(new Element('div', {
text: str
}));
});
}
$("process").addEvent('click', function() {
var text = $('input').get('value').trim();
var tips = text.split('\n').map(function(line) {
var values = line.split(' ');
return new Tip(values[0], values[1]);
});
console.log(tips);
process(tips);
});