how can i find the highest number in the array and sort the array so it has the highest numbers first?
I am using jQuery also, if that should make it easier. I cannot figure out how to sort it, and then outputs the sorted arrays with html into usersInRoom div.
Hope someone can help me though this!
I have readed a little bit about the "max" in javascript, but it was complicate, and didn't match my code.
I will sort the mydivs[.......]['number'] and not mydivs, because it contains an array in an array.
<div id="usersInRoom">
<div class="entry in_room" id="userInRoom-2" style="background-color: rgb(255, 255, 255);">
<table style="width:100%">
<tbody>
<tr>
<td style="width:32px">
<img
src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn1/c33.33.414.414/s200x200/996882_221295918024677_1913237122_n.jpg"
style="height:32px;width:32px">
</td>
<td style="vertical-align:middle"><strong>Stefanie Pedersen</strong>
</td>
<td align="right" style="vertical-align:middle;color:#999"><span id="exp-2" class="exp">6</span> exp.
</td>
</tr>
</tbody>
</table>
</div>
<div class="entry in_room" id="userInRoom-1" style="background-color: rgb(155, 229, 162);">
<table style="width:100%">
<tbody>
<tr>
<td style="width:32px">
<img
src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc1/c176.49.608.608/s200x200/429356_10151257167066983_1091687280_n.jpg"
style="height:32px;width:32px">
</td>
<td style="vertical-align:middle"><strong>Bare Kald Mig Jesper</strong>
</td>
<td align="right" style="vertical-align:middle;color:#999"><span id="exp-1" class="exp">14</span> exp.
</td>
</tr>
</tbody>
</table>
</div>
</div>
And here is my jQuery code to insert the HTML and the numbers into array, after this it should "just" sort it and outputs it again.
<script>
var numbers = [];
var mydivs = [];
var arr = $("#usersInRoom").find(".exp");
$.each(arr, function (e) {
var eq = arr[e];
console.log(eq);
mydivs.push({
"html": $(eq).parents(".entry").parents("div").html(),
"number": parseInt($(eq).text())
});
});
</script>
I WILL SORT THE mydivs[.......]['number'] <----
This one should work with more than 2 elements:
var aRows = jQuery.makeArray($('#usersInRoom').children());
aRows.sort(function(a,b) {
return parseInt($(b).find('.exp').text()) -
parseInt($(a).find('.exp').text());
});
$('#usersInRoom').empty().append(aRows);
I don't know what your array looks like but I think that you can use the JavaScript sort method.
var NumbersArray = [400,200,600,300,1000];
var SortedArray = NumbersArray.sort(function(a,b){return b-a});
alert(SortedArray);
http://www.w3schools.com/jsref/jsref_sort.asp
If you want to find the highest number before sorting you can try something like this:
var NumbersArray = [400,200,600,300,1000];
var MaxPreviousNumber = 0;
for (var i = 0; i <= NumbersArray.length; i++) {
var MaxPreviousNumber = Math.max(MaxPreviousNumber, NumbersArray[i]);
}
I think this is doing what you want:
http://jsfiddle.net/j8bLc/2/
var arr = $("#usersInRoom").find(".exp");
$.each(arr, function (key, el) {
var curr = parseInt($(el).text());
var top = parseInt($("#usersInRoom .exp").eq(0).text());
if(curr > top) {
$(el).closest(".entry").prependTo('#usersInRoom');
}
});
But there might be a better solution with less DOM manipulations.
To print your array data in reverse order you can find array length like,
for(var i=mydivs.length-1;i>=0;i++)
{
console.log(mydivs[i]['html']);
}
Fiddle
If you will look closer here: http://www.w3schools.com/jsref/jsref_sort.asp, you can see that sort has a parameter - your own sorting function which you can use.
So, you can sort the array using you own comparing function
function compare(a,b) {
if (a.number < b.number)
return -1;
if (a.number > b.number)
return 1;
return 0;
}
objs.sort(mydivs);
this will sort your array
Related
Title might be a bit confusing, but this is the best I could come up with.
I need to find all tr elements which contains td elements matching the filter criteria provided.
Here is my sample,
<tr class="row" id="1">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="lamp">Lamp<td>
</tr>
<tr class="row" id="2">
<td class="philips">PHILIPS</td>
<td class="h5">H5</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="3">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="4">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="5">
<td class="osram">OSRAM</td>
<td class="hb3">HB3</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="6">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="lamp">Lamp<td>
</tr>
If I pass filter[0] as 'phillips', the result return tr with id
1
2 and
4
Then if I pass second filter; filter[1] as 'h4', the result should be filtered down to
1 and
4
I have tried this question.
Which has this answer.
$('tr')
.has('td:nth-child(1):contains("Audi")')
.has('td:nth-child(2):contains("red")')
.doSomeThing();
But, I want my filters to be applied dynamically. How would I be able to insert a 3rd has function?
I don't want to go the if-else or switch-case way, if this is possible with out them.
You can try this.
<script type="text/javascript">
$(document).ready(function () {
var result = filter([".philips", ".h4"]);
alert(result);
var result_2 = filter([".philips"]);
alert(result_2);
});
function filter(params) {
var select = "tr";
for (var i = 0; i < params.length; i++) {
select += ":has(" + params[i] + ")";
}
return $(select).map(
function () {
return $(this).attr('id');
}
).get();
}
</script>
if you have an array of filters needed, iterate that array and pass the filter string to the has?
var filters = ['PHILIPS', 'H4', 'Bulb']
var result = $('tr');
for(var i = 0; i < filters.length; i++){
var nchild = i+1;
result = result.has('td:nth-child('+nchild+'):contains("+'filters[i]'+")');
}
edit to your needs of course, but this way you can take user input, compile that into the needed array and then iterate whatever is in the array to filter down results.
You should wrap the $.has() into a separate function (I've just used jquery's easy extensions supports) which will expose the usage as a composite function chain via javascript's syntax...
$( document ).ready(function() {
$('tr')
.nthFilter('td:nth-child(1):contains("PHILIPS")')
.nthFilter('td:nth-child(2):contains("H4")')
.nthFilter('td:nth-child(3):contains("Bulb")')
.css("background-color", "red");
});
jQuery.fn.extend({
nthFilter: function(filter) {
return $(this).has(filter);
}
});
I've put together a small jsfiddle for you to fiddle with :)
You can supply your filter as a string:
var filter = ".philips, .h4";
$("tr").has("td").has(filter).map(function() { return this.id; });
// returns ["1", "2", "4"]
and if you want the elements then obviously leave the map off:
$("tr").has("td").has(filter);
// returns array of <tr>
Edit: Just noticed you want recursive filtering so change the filter to use sibling selector ~.
var filter = ".philips ~ .h4";
// returns ["1", "4"]
So if you want a third level then just:
var filter = ".philips ~ .h4 ~ .bulb";
// returns ["4"]
Hello experts,
Could you please recommend:
I have two tables:
<tr id='firs_table'>
<td id="team">team1</td><td>45</td>
<td id="team">team2</td><td>47</td>
</tr>
<tr id='second_table'>
<td id="team">team1</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team1</td><td id="service">service name2</td><td id="count">count2</td>
<td id="team">team1</td><td id="service">service name3</td><td id="count">count3</td>
<td id="team">team2</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team2</td><td id="service">service name2</td><td id="count">count2</td>
</tr>
I need to create dictionary like:
team1: ['service name1','service name2','service name3'], [count1,count2, count3]
team2: ['service name1','service name2'], [count1,count2]
could you please advise algorithm with jquery ?
I need that result in order create RGraph graph.
Thank you in advance.
I could not provide any working example of jquery code, I could not find a way how to iterate over $("tr#first_table td"#team") value and compare it with $("tr#second_table td"#team"), if values are the same => return array of [[$("tr#second_table td"#service")], [$("tr#second_table td"#count")] ].
I mean, I could not find idea.
This should do what you need
var res = {}
$('table tr').each(function () {
var cellText = $(this).find('td').map(function (i, el) {
return $(el).text();
}).get();
if (!res[cellText[0]]) {
res[cellText[0]] = [[],[]];
}
res[cellText[0]][0].push(cellText[1]);
res[cellText[0]][1].push(cellText[2]);
});
If you have a heading row can use $('table tr:gt(0)')
DEMO
I'm working on a small userscript to sort a table, the structure of the table is really weird however. What i'm trying to do is to add an extra sort feature so I can sort on the ranking (#) of the persons.
Table data looks like this:
<table id="outer">
<tr>
<td><div id="bgn"></div></td>
<td>User 1</td>
<td>
<table id="inner">
<tbody>
<tr>
<td>Rank</td>
<td id="tdp">#28</td>
</tr>
</tbody>
</table>
</td>
</tr>
<!-- more rows -->
</table>
There are some additional <td>'s but they are not important right now. There are about 52 rows, but these could vary, of course.
Current jQuery code I have:
jQuery( document ).ready(function() {
var rankings = [];
$(document).on('click', '#tdr', function() {
// skipping first line because it's the header
$('tr:not(:first-child').each(function () {
var rank = $(this).find('#tdp').text();
var rank2 = rank.substring(1, rank.length)
rankings.push(rank2);
});
console.log(rankings.sort(sortNumber));
});
function sortNumber(num1, num2) {
return num1 - num2;
}
});
JS Bin Example
The output in the console is a correctly sorted array with all the rankings, I just don't have any idea how to also swap the corresponding <tr>'s so that the table get's rebuild the right way. Looking for any tips or pointers!
This suggestion is not really into "sorting" the rows, but re-constructing the table with the sorted rows. But this should do the job:
rankings = rankings.sort(sortNumber);
var table = $('<table></table>');
for (var i = 0; i < rankings.length; i++) {
var row = $('tr').filter(function() {
var rank = $(this).find('#tdp').text();
return rank.substring(1, rank.length) == i;
});
table.append(row);
}
$('#originalTable').html(table.html());
I have a html table that looks like this...
<table>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</table>
<p>Total number is:MULTIPLICATION OF ALL CHANCE COLUMN TD</p>
all my rows are added dynamically,how do i multiply all chance column td values(numbers)?Do i have to put certain class on chance tds and then get all tds with that class,and loop through and multiply every value then?I'm kinda a newbie so any help would be appreciated.
You can either do something like this:
var tots = 1;
$('tr td:nth-child(4)').each(function(){
tots *= $(this).text();
});
the nth-child(4) is selecting the fourth td in each row, if you want another, just change that number.
or you can give the cells you want to multiple classes, like you said.
example here
If you're using jQuery, the :last-child selector could be helpful.
<p>Total number is: <span id="result"></span></p>
Javascript:
res = 1;
$("tr td:last-child").each(function() {
res *= parseFloat($(this).html());
});
$("#result").html(res);
Have a look to this JSFiddle.
You don't need jQuery to do this. querySelectorAll supports nth-child selector as well.
var derp = document.querySelectorAll("tr td:nth-child(4)");
var total = 1;
var results = [].reduce.call(derp, function (prev, next) {
return prev * ( + next.textContent );
});
Grab the element, and use native Array prototype methods ([]) to iterate the NodeList and return the parsed value of the element, then return the multiplied total.
Here is a fiddle for you.
$(function () {
var chanceTotals = 1;
$("tr td:nth-child(4)").each(function () {
chanceTotals *= parseFloat($(this).html());
});
$("#totals").html("Total number is: " + chanceTotals);
});
Using jQuery, this executes an anonymous function when the document is ready that will do the calculation for you.
You will need to add the id totals to your p element in order for this to work.
Look at this JSFiddle
You really do not need jquery at all to do this. Interacting with the DOM directly may make you write more (browser support), but it can be more efficient than using jQuery (Unnecessary overhead).
As you can see, I restructured your <table>. I could have just grabbed the <tbody> and looped over its children and skipped the whole if <TD> ? check.
DEMO
$(document).ready(function () {
var table = $('#myTable').get(0);
var multiplier = 1;
var col = 3;
for (var row = 0; row < 4; row++) {
var cell = table.rows[row].cells[col];
if (cell.nodeName == 'TD') {
var text = cell.innerText || cell.textContent;
multiplier *= parseFloat(text);
}
}
$('#multiplier').text(multiplier);
});
<table id="myTable">
<thead>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
</thead>
<tbody>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</tbody>
</table>
<p>Total number is:
<span id="multiplier">MULTIPLICATION OF ALL CHANCE COLUMN TD</span>
</p>
I have a a and I would like to sort my list alphabetically (I don't want caps to matter) according to a class named "name". How would I do this?
<ul class="column">
<li>
<table>
<tr>
<td class="name" >Name of Item</td>
</tr>
<tr>
<td>Content</td>
</tr>
<tr>
<td>morecontent</td>
<td>morecontent</td>
</tr>
</table>
</li>
<li>
<table>
<tr>
<td class="name" >Another name of item</td>
</tr>
<tr>
<td>Content</td>
</tr>
<tr>
<td>morecontent</td>
<td>morecontent</td>
</tr>
</table>
</li>
</ul>
Thanks
Using jQuery, this should do it:
function sort() {
$($('ul.column>li').get().reverse()).each(function(outer) {
var sorting = this;
$($('ul.column>li').get().reverse()).each(function(inner) {
if($('td.name', this).text().localeCompare($('td.name', sorting).text()) > 0) {
this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
}
});
});
}
The above is a little dense though, so if you want to understand what's going on, let's break it down line-by-line:
function sort() {
//get each <li> which is a child of <ul class="column">
//for each element in the results, execute a function
//also, we reversed the order (e.g. start at the bottom and go up
$($('ul.column>li').get().reverse()).each(function(outer) {
//this is the current <li> we're running against
var sorting = this;
//get the same set of elements again in their current state,
//so we can figure out where to put this one
$($('ul.column>li').get().reverse()).each(function(inner) {
//get the inner text of the <td class="name">
//for the item we're trying to replace,
//and for the current item in the inner loop
//use localeCompare to compare the two strings alphabetically
if($('td.name', this).text().localeCompare($('td.name', sorting).text()) > 0) {
//if the one we're trying to sort goes after the current one
//alphabetically, remove it from its current position
//and insert it after the current one
this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
}
});
});
}
We can make it a little more reusable by passing in the selector for the list and the key:
sort('ul.column>li', 'td.name');
function sort(list, key) {
$($(list).get().reverse()).each(function(outer) {
var sorting = this;
$($(list).get().reverse()).each(function(inner) {
if($(key, this).text().localeCompare($(key, sorting).text()) > 0) {
this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
}
});
});
}
Do keep in mind this requires jQuery, so you'll need a reference to it in your <head>:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
And this function should be called at some point in the page after the list is written in the HTML.
Mine answer is longer :p but work.
function SortLIs() {
var ColumnUL = $("ul.column");
var Columns = $(ColumnUL).children("li");
var ColumnNames = new Array();
var Columns_byName = new Array();
var Columns_Count = Columns.length;
for(var i = 0; i < Columns_Count; i++) {
var aColumn = Columns[i];
var aTD = $(aColumn).find(".name");
var aTDName = aTD.text();
ColumnNames.push(aTDName);
Columns_byName[aTDName] = aColumn;
$(aColumn).remove();
}
ColumnNames.sort(function(a, b){
return (a > b) - (a < b);
});
for(var i = 0; i < Columns_Count; i++) {
var aName = ColumnNames[i];
ColumnUL.append(Columns_byName[aName]);
}
}
EDIT: I saw you said that you are not good at JS. So here is the bigger picture for you.
(1) Add The following code to the header of the HTML. This will use jQuery library.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
(2) Add the 'sortLIs' code just right after the above code
<script>
<!--
function SortILs() {
...
}
-->
</script>
(3.1) If you want the sorting to begin at the load time. Add this right after the above code.
<script>
<!--
$(document).ready(function(){
SortILs();
});
-->
</script>
(3.2) Otherwise, you call the function from an event.
Hope this helps.
Here's another approach, stealing ideas from the other answers given so far (also requiring jQuery):
function sort(elementSelector, valueSelector, ascending) {
var sign = ascending ? -1 : 1;
var elements = jQuery(elementSelector);
elements.each(function() {
this.sortKey = jQuery(valueSelector, this).text();
});
var sorted = elements.get();
sorted.sort(function(a, b) {
var keyA = a.sortKey;
var keyB = b.sortKey;
return sign * ((keyA < keyB) - (keyA > keyB));
});
elements.parent().append(sorted);
}
sort('.column>li', '.name', true)
Just seconding the jQuery response above, have a look at this tutorial:
http://www.shopdev.co.uk/blog/sortable-lists-using-jquery-ui/
For semantics, you might be better off also placing the classname inside the actual <li> tag.
The use of a table inside a list aside though, you may want to post an example page to help further.