Sorting a list alphabetically with a modulus - javascript

I don't have any trouble grabbing a list of elements and sorting them alphabetically, but I'm having difficulty understanding how to do it with a modulus.
### UPDATE ###
Here's the code working 'my way', however, I like the re-usability of the answer provided below more, so have accepted that answer.
<script type="text/javascript">
$(document).ready( function() {
$('.sectionList2').each( function() {
var oldList = $('li a', this),
columns = 4,
newList = [];
for( var start = 0; start < columns; start++){
for( var i = start; i < oldList.length; i += columns){
newList.push('<li>' + $(oldList[i]).text() + '</li>');
}
}
$(this).html(newList.join(''));
});
});
</script>
For example. Say I have the following unordered list:
<ul>
<li>Boots</li>
<li>Eyewear</li>
<li>Gloves</li>
<li>Heated Gear</li>
<li>Helmet Accessories</li>
<li>Helmets</li>
<li>Jackets</li>
<li>Mechanic's Wear</li>
<li>Pants</li>
<li>Protection</li>
<li>Rainwear</li>
<li>Random Apparel</li>
<li>Riding Suits</li>
<li>Riding Underwear</li>
<li>Socks</li>
<li>Vests</li>
</ul>
I have this list set to display in 4 columns with each li floated right. Visually this makes finding items in larger lists difficult. The output I need is this:
<ul>
<li>Boots</li>
<li>Helmet Accessories</li>
<li>Pants</li>
<li>Riding Suits</li>
<li>Eyewear</li>
<li>Helmets</li>
<li>Protection</li>
<li>Riding Underwear</li>
<li>Gloves</li>
<li>Jackets</li>
<li>Rainwear</li>
<li>Socks</li>
<li>Heated Gear</li>
<li>Mechanic's Wear</li>
<li>Random Apparel</li>
<li>Vests</li>
</ul>
What I'm looking for is a function that I can pass my array of list items and get my array returned, sorted alphabetically, with a modulus of choice; in this case 4.
Any help would be appreciated as I can find no documentation on the subject.

Alphabetize your list. This is already done, in your case, but if not:
function alphabetizeElements(a, b)
{
var aText = $(a).text();
var bText = $(b).text();
return aText > bText ? 1 : aText < bText ? -1 : 0;
}
var alphabetizedList = $("#myList li").sort(alphabetizeElements);
Store the alphabetized index of each element:
$.each(alphabetizedList, function(i)
{
$(this).data("alphaIndex", i);
});
Sort the alphabetized list by modulus first, then index:
function listColumnSortFn(columns)
{
return function(a, b)
{
var aIndex = $(a).data("alphaIndex");
var bIndex = $(b).data("alphaIndex");
return ((aIndex % columns) - (bIndex % columns)) || (aIndex - bIndex);
}
}
var columnSortedList = alphabetizedList.sort(listColumnSortFn(4));
Replace the list elements with your sorted elements:
$("#myList li").remove();
$("#myList").append(columnSortedList);
Here is the whole thing, all together:
function sortList(columns)
{
var alphabetizedList = $("#myList li").sort(alphabetizeElements);
$.each(alphabetizedList, function(i)
{
$(this).data("alphaIndex", i);
});
var columnSortedList = alphabetizedList.sort(listColumnSortFn(columns));
$("#myList li").remove();
$("#myList").append(columnSortedList);
}
function alphabetizeElements(a, b)
{
var aText = $(a).text();
var bText = $(b).text();
return aText > bText ? 1 : aText < bText ? -1 : 0;
}
function listColumnSortFn(columns)
{
return function(a, b)
{
var aIndex = $(a).data("alphaIndex");
var bIndex = $(b).data("alphaIndex");
return ((aIndex % columns) - (bIndex % columns)) || (aIndex - bIndex);
}
}
$(function()
{
sortList(4);
});

var columnify = function (a,n) {
var result = [];
for (var i = 0, lastIndex = a.length - 1; i < lastIndex; i++)
result.push(a[i * n % (lastIndex)]);
result[lastIndex] = a[lastIndex];
return result;
}
var products = ["Boots",
"Eyewear",
"Gloves",
"Heated Gear",
"Helmet Accessories",
"Helmets",
"Jackets",
"Mechanic's Wear",
"Pants",
"Protection",
"Rainwear",
"Random Apparel",
"Riding Suits",
"Riding Underwear",
"Socks",
"Vests",]
columnify(products, 4)
["Boots", "Helmet Accessories", "Pants", "Riding Suits", "Eyewear", "Helmets", "Protection", "Riding Underwear", "Gloves", "Jackets", "Rainwear", "Socks", "Heated Gear", "Mechanic's Wear", "Random Apparel", "Vests"]
Apply that function to the already sorted list, and then it will return a list of strings in the order (almost) that you want. Then add the list that was returned in order to the unordered list in the DOM.
Also, I haven't tested it with anything besides that list. So I'd do that if I were you. From what I see, it only works if the length of the list is a multiple of n. Not that great of a solution but it's late for me and I can't be bothered to come up with anything better.
EDIT: fixed the issue with the last element

See if this will work: http://jsfiddle.net/6xm9m/2
var newList = new Array();
var listItem = $('#list > li');
var mod = 4;
var colCount = Math.ceil(listItem.length / mod);
listItem.each(function(index) {
var newIndex = ((index % colCount) * mod) + Math.floor(index / colCount);
// $(this).text(newIndex);
newList[newIndex] = this;
});
$('#list').empty();
for(var i = 0; i < newList.length; i++){
$('#list').append(newList[i]);
}
Needs improvements, probably, but I'm not really sure how well this works at all.

Here you go. The code is surprisingly simple once you figure it out. I realize you are using jQuery but I'm not familiar enough with it to use its features. This is simple enough that maybe it's not necessary.
function pivotArray(arr, columns) {
var l = arr.length, out = [], ind = 0, i = 0;
for (; i < l; i += 1) {
out[ind] = arr[i];
ind += columns;
if (ind >= l) {
ind = ind % columns + 1;
}
}
return out;
}
And here's the test to prove it works (tested in Firefox 3.6.9, IE 6, Chrome 1.0.154.36):
<html>
<head>
<style type="text/css">
a.panelnum {
display:block;
float:left;
width:40px;
height:40px;
border:1px solid black;
text-align:center;
vertical-align:middle;
text-decoration:none;
font-size:2em;
}
</style>
</head>
<body onload="doit(17, 4);">
<div id="output" style="border:1px solid blue;">
</div>
<script type="text/javascript">
function pivotArray(arr, columns) {
var l = arr.length, out = [], ind = 0, i = 0;
for (; i < l; i += 1) {
out[ind] = arr[i];
ind += columns;
if (ind >= l) {
ind = ind % columns + 1;
}
}
return out;
}
function doit(size, columns) {
document.getElementById('output').innerHTML = 'starting';
var l = size;
var inp = [];
for (var i = 0; i < l; i += 1) {
inp[i] = i;
}
var result = pivotArray(inp, columns);
var str = '';
for (i = 0; i < l; i += 1) {
str += '<a class="panelnum">' + result[i] + '</a>';
}
var d = document.getElementById('output')
d.innerHTML = '<p>Some pre text</p>' + str + '<p style="clear:both;">and some post text</p>';
d.style.width = (columns * d.childNodes[1].offsetWidth + 2) + 'px';
}
</script>
</body>
</html>
One more thing: it might be useful to just move the elements around in-place. I almost had script for it but my script was running backwards (as if floats went from top to bottom first). If I get time I'll work on it and post the code.
P.S. Anyone want to give me pointers on why I had to add 2 to the width calculation for IE6? Wait... it's the borders of the div isn't it?

Related

How to create real-time changes in JavaScript

So I wrote a pretty basic code. I'm a real noob. Started JavaScript 3 days back. I want the sorting process to be visualized while the sorting is going on. But when the SORT button is clicked after a while the sorted array is show. But what I want is to show the changes happening to the array in real-time.
Please help me out.
var array = [];
container_content= "";
for (var i=0; i < 50; i++) {
array.push(Math.random() *500)
}
container_content = "";
function myFunction(element) {
container_content += '<div class="array-bar"></div>';
}
array.forEach(myFunction);
$(".container").html(container_content);
function another(element, index){
element.style.height = array[index]
}
$( "div" ).each( function( index, element ){
$( this ).css('height', array[index]);
});
$('button').click(function(){
var i, j, temp;
for(i = 0; i < array.length; i++)
{
for(j = 0; j < array.length-1; j++)
{
if( array[j] > array[j+1])
{
// swap the elements
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
$( "div" ).each( function( index, element ){
$( this ).css('height', array[index]);
});
}
})
I took what you were trying to do and broke it down into 4 basic functions (1 main function and 3 helper functions).
runSort is the main function that uses all the other helper functions to do everything.
makeArrayAndUnsyncedBars generates your random array and basic divs that you'll use as green "bars", but it doesn't set the heights of these divs according to the values in the array.
syncArrayToBars sets the heights of these "bar" divs according to the values in the array
sortUntilNextSwap sorts the array until either a swap occurs or the sort completes. this function returns false if it made a swap (meaning that it's still working its way through the array) or true otherwise.
var FRAMES_PER_SECOND = 50;
var sortInterval = null;
function runSort() {
clearInterval(sortInterval);
makeArrayAndUnsyncedBars(50);
syncArrayToBars();
sortInterval = setInterval(function() {
var finishedSorting = sortUntilNextSwap();
syncArrayToBars();
if (finishedSorting) clearInterval(sortInterval);
}, Math.round(1000 / FRAMES_PER_SECOND));
}
var array = [];
function makeArrayAndUnsyncedBars(numberOfValues) {
var htmlToAdd = "";
array = [];
for (var i = 0; i < numberOfValues; i++) {
htmlToAdd += "<div class=\"bar\"></div>";
array.push(rando(150));
}
$("#bars").html(htmlToAdd);
}
function syncArrayToBars() {
for (var i = 0; i < array.length; i++) $(".bar").eq(i).css({
height: array[i] + "px"
});
}
var i, j, temp;
function sortUntilNextSwap() {
for (i = 0; i < array.length; i++) {
for (j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
// swap the elements
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
return false;
}
}
}
return true;
}
.bar {
width: 5px;
background: #5aedab;
border-radius: 3px;
display: inline-block;
margin: 0px 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://randojs.com/1.0.0.js"></script>
<div id="bars"></div>
<button onclick="runSort();">Run sort</button>
EDIT: I should mention that I used rando.js for the randomness out of habit, but it's not super necessary here given that you use Math.random() very little anyway. Take it out or leave it in according to your preference.

Font Size changes according to count of word

function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>

Assigning a value to a global variable through input method

Good day. Have patience first of all since I am just a new enthusiast to Javascript and programming in general. The concern about my project is that I want to assign a value to a global variable through input method and run it through. I've tried, researched and nothing more work for me at this time. So I am asking anyone for ideas, how will it be possible. Your assistance will definitely help me in my learning process.
Initially, the code looks likes this: Here the global variable numItems is defined by 30. That variable numItems is also mentioned within two other functions below. What I want to do is change that number through input method. I've tried...
numItems = 30;
var xvalue = [];
var yvalue = [];
for (var i=0; i < numItems; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
followed by several functions....
This is my try, but it seems this is not working... Any assistance will be greatly appreciated.
numItems = document.getElementById("numInput");
numItems.addEventListener("input", whatValue);
function whatValue() {
var num = parseFloat(numItems.value);
document.getElementById("numInput") = num;
}
var xvalue = [];
var yvalue = [];
for (var i=0; i < numItems; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
followed by several functions....
Here is the whole code when I applied Michael's suggestions below: It works, but my concern now are the undefined variables in the output---> undefined + undefined or undefined - undefined
<body>
<input id="numInput">
<select id="processMath">
<option value="add">Addition</option>
<option value="sub">Subtraction</option>
</select>
<button onclick="newExercise()">New Exercise</button>
<button onclick="createExercise()">Create Exercise</button>
<div id="tableOne"></div>
</body>
<script type="text/javascript">
numItems = document.getElementById("numInput");
numItems.addEventListener("input", whatValue);
function whatValue() {
numItems = parseFloat(document.getElementById("numInput").value);
}
xvalue = [];
yvalue = [];
for (var i=0; i<numItems ; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
function tableOne (operator) {
var valtp = '';
var spc = '<table border="1" width="80%"><tr>';
i = 0;
while (i < numItems ) {
a = xvalue[i];
b = yvalue[i];
spc += '<td align="right">'+a;
if (operator == 'add') { spc += '<br>+ '+b; valtp = a+b; }
if (operator == 'sub') { spc += '<br>- '+b; valtp = a-b; }
spc += '<br>_____';
i++;
if ((i % 5) == 0) { spc += '</tr><tr>'; }
}
spc += '</tr></table>';
return spc;
}
function createExercise() {
var a = 0; var b = 0; var spc = '';
var spc = '';
var sel = document.getElementById('processMath').value;
switch (sel) {
case 'add' : spc += tableOne(sel); break;
case 'sub' : spc += tableOne(sel); break;
}
document.getElementById('tableOne').innerHTML = spc;
}
function makeRandom() {
return (Math.round(Math.random())-0.5);
}
function newExercise() {
xvalue.sort(makeRandom);
yvalue.sort(makeRandom);
}
</script>
Unless I've misunderstood you, it looks like your whatValue() function is trying to change the input value, instead of changing the numItems variable, but it's failing on both counts.
function whatValue() {
var num = parseFloat(numItems.value);
document.getElementById("numInput") = num;
}
Should be:
function whatValue() {
numItems = parseFloat(document.getElementById("numInput").value);
}
Now, your numItems variable should change every time numInput changes.
But, even though numItems changes, it won't make the rest of your code run again. So your two arrays will still look like they did when numItems was 30.

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

How to sort <ul><li>'s based on class with javascript?

I have a TODO list app with an Unordered list. Within it I have a few list items. The li classes are high,medium,low. I would like li's with the class high to be placed before li's with the class medium and last ones with low.
<ul id="tasks">
<li id="item3" class="priority low"><span></span><span>This is a low priority task</span></li>
<li id="item4" class="priority high"><></span><span>This is a high priority task</span></li>
<li id="item5" class="priority low"><span></span><span>This is another Low</span></li>
<li id="item7" class="priority medium"><span></span><span>And now a Medium</span></li>
</ul>
So the li with id of item4 should be first and then it should be item7 and then the li's with class low after.
Here's a pure JS version of #ŠimeVidas jQuery solution.
var tasks = document.querySelector('#tasks'),
items = document.querySelectorAll('#tasks > li');
for (var i = 0, arr = ['high', 'medium', 'low']; i < arr.length; i++) {
for (var j = 0; j < items.length; j++) {
if (~(" " + items[j].className + " ").indexOf(" " + arr[i] + " "))
tasks.appendChild(items[j]);
}
}
Assuming you can use jQuery, and assuming your list is not very big, and assuming you've only got these three fixed types with no plans on changing this, I'd probably just dump the whole set into memory, clear out the list, then put them back in the list in order. Something like:
jQuery(document).ready(function() {
var i;
var items = jQuery("#tasks li");
var lowItems = [];
var medItems = [];
var highItems = [];
for (i = 0; i < items.length; ++i) {
var jqItem = jQuery(items[i]);
if (jqItem.hasClass("low")) lowItems.push(jqItem);
if (jqItem.hasClass("medium")) medItems.push(jqItem);
if (jqItem.hasClass("high")) highItems.push(jqItem);
}
var tasks = jQuery("#tasks");
tasks.html("");
for (i = 0; i < highItems.length; ++i) {
tasks.append(highItems[i]);
}
for (i = 0; i < medItems.length; ++i) {
tasks.append(medItems[i]);
}
for (i = 0; i < lowItems.length; ++i) {
tasks.append(lowItems[i]);
}
});
Try this:
$(function(){
var sorter = [],
tasks = $('#tasks');
$('li.priority').each(function(){
var $this = $(this),
priority = $this.hasClass('high') ? 3 : ($this.hasClass('medium') ? 2 : 1);
sorter.push({
el : this,
priority : priority
});
}).detach();
sorter.sort(function(a, b){
return a.priority - b.priority;
});
$.each(sorter, function(){
tasks.append(this.el);
});
});
With no jquery:
<ul id="tasks">
<li id="item3" class="priority low"><span></span><span>This is a low priority task</span></li>
<li id="item4" class="priority high"><></span><span>This is a high priority task</span></li>
<li id="item5" class="priority low"><span></span><span>This is another Low</span></li>
<li id="item7" class="priority medium"><span></span><span>And now a Medium</span></li>
</ul>
<script type="text/javascript">
var tasks = document.getElementById("tasks");
var liElements = tasks.getElementsByTagName("li");
var lowPriority = [];
var mediumPriority = [];
var highPriority = [];
var removal = [];
for (var i = 0, len = liElements.length; i < len; i++) {
if (liElements[i].getAttribute("class").indexOf("low") > -1) lowPriority.push(liElements[i].cloneNode(true));
if (liElements[i].getAttribute("class").indexOf("medium") > -1) mediumPriority.push(liElements[i].cloneNode(true));
if (liElements[i].getAttribute("class").indexOf("high") > -1) highPriority.push(liElements[i].cloneNode(true));
removal.push(liElements[i]);
}
for (var i = 0, len = removal.length; i < len; i++ ) {
var liItem = removal[i];
liItem.parentNode.removeChild(liItem);
}
for( var i = 0, len = lowPriority.length; i < len; i++){
tasks.appendChild(lowPriority[i]);
}
for (var i = 0, len = mediumPriority.length; i < len; i++) {
tasks.appendChild(mediumPriority[i]);
}
for (var i = 0, len = highPriority.length; i < len; i++) {
tasks.appendChild(highPriority[i]);
}
</script>
Here's another jQuery–less option:
// Just a helper
function toArray(obj) {
var result = [];
for (var i=0, iLen=obj.length; i<iLen; i++) {
result[i] = obj[i];
}
return result;
}
// Uses querySelectorAll, but could use getElementsByTagName instead
function sortByPriority(id) {
var nodes;
var el = document.getElementById(id);
if (el) {
nodes = toArray(el.querySelectorAll('li.priority'));
nodes.sort(function(a, b) {
function getIndex(el) {
return el.className.indexOf('low') != -1? 1 :
el.className.indexOf('medium') != -1? 2 :
el.className.indexOf('high') != -1? 3 :
0; // default
}
return getIndex(b) - getIndex(a);
});
for (var i=0, iLen=nodes.length; i<iLen; i++) {
el.appendChild(nodes[i]);
}
}
}
It uses a few more lines that a jQuery (or perhaps any library) based solution but you don't have to load several thousand lines of library either.
Also, this runs about 5 times faster in Firefox and IE 9 and 10 times faster in Chrome than a jQuery solution (see http://jsperf.com/sortelementlist).
With pure JavaScript, and simple code!
var tasks = document.getElementById("tasks");
var lis = tasks.getElementsByTagName("li");
var lisarr = Array.prototype.slice.call(lis);
var priority = function(e){
var prio = {low: 0, medium: 1, high: 2};
return prio[e.getAttribute("class").match(/low|high|medium/)[0]];
};
lisarr.sort(function(a,b){
var ap = priority(a), bp = priority(b);
return bp - ap;
});
tasks.innerHTML = lisarr.reduce(function(prev, current){
return prev + current.outerHTML;
}, '');

Categories

Resources