logo
Tags down

shadow

Sort table both numerically and alphabetically using Javascript


By : chuckt62
Date : October 17 2020, 03:08 PM
I wish this helpful for you you should parse the numeric values as integer or float before comparsion
so
code :
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
if (parseInt(x.innerHTML) > parseInt(y.innerHTML)) {
var cmpX=isNaN(parseInt(x.innerHTML))?x.innerHTML.toLowerCase():parseInt(x.innerHTML);

var cmpY=isNaN(parseInt(y.innerHTML))?y.innerHTML.toLowerCase():parseInt(y.innerHTML);

if (parseInt(cmpX) > parseInt(cmpY)) {
function sortTable(tableClass, n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;

table = document.getElementsByClassName(tableClass)[0];
switching = true;
dir = "asc";
while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 1); i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
                var cmpX=isNaN(parseInt(x.innerHTML))?x.innerHTML.toLowerCase():parseInt(x.innerHTML);
                var cmpY=isNaN(parseInt(y.innerHTML))?y.innerHTML.toLowerCase():parseInt(y.innerHTML);
cmpX=(cmpX=='-')?0:cmpX;
cmpY=(cmpY=='-')?0:cmpY;
        if (dir == "asc") {
            if (cmpX > cmpY) {
                shouldSwitch= true;
                break;
            }
        } else if (dir == "desc") {
            if (cmpX < cmpY) {
                shouldSwitch= true;
                break;
            }
        }
    }
    if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        switchcount ++;      
    } else {
        if (switchcount == 0 && dir == "asc") {
            dir = "desc";
            switching = true;
        }
    }
}
}


Share : facebook icon twitter icon

How can I sort a javascript array of objects numerically and then alphabetically?


By : EJ-HGPIT
Date : March 29 2020, 07:55 AM
I wish this helpful for you , I think it's better done just with...
code :
items.sort(function(a, b) { 
  return a.id - b.id  ||  a.name.localeCompare(b.name);
});
items.sort(function(a, b) { 
  return - ( a.id - b.id  ||  a.name.localeCompare(b.name) );
});

C++ Sort Map By Value Numerically, Key Alphabetically


By : user3599889
Date : March 29 2020, 07:55 AM
like below fixes the issue Not sure why you're using std::partial_sort here - it's meant for sorting only part of the input. Try std::stable_sort instead: it will sort the input, but will not affect the order of elements that compare equal. This gives you what you want since your input map is already sorted by increasing alphabetical key:
code :
struct IntCmp {
    bool operator()(const mypair &lhs, const mypair &rhs) {
        return lhs.second > rhs.second; // note reversed comparison here to sort by descending order
    }
};

void printmap(const std::map<std::string,int> &mymap, int size) {
    std::vector<mypair> myvec(mymap.begin(), mymap.end());
    assert(myvec.size() >= size);
    std::stable_sort(myvec.begin(), myvec.end(), IntCmp());

    // note we now iterate forwards because the sort comparison is reversed
    for(const auto &item : myvec) {
        std::cout << item.first << " " << item.second << "\n";
    }
}
struct IntCmp {
    bool operator()(const mypair &lhs, const mypair &rhs) {
        if(lhs.second == rhs.second) return lhs.first < rhs.first; // this is the "secondary" comparison, used if the frequencies are equal
        return lhs.second > rhs.second; // note reversed comparison here to sort by descending order
    }
};

void printmap(const std::map<std::string,int> &mymap, int size) {
    std::vector<mypair> myvec(mymap.begin(), mymap.end());
    assert(myvec.size() >= size);
    std::sort(myvec.begin(), myvec.end(), IntCmp());

    // note we now iterate forwards because the sort comparison is reversed
    for(const auto &item : myvec) {
        std::cout << item.first << " " << item.second << "\n";
    }
}

How to sort a table column numerically and alphabetically?


By : user3632792
Date : March 29 2020, 07:55 AM
This might help you Answer was available in the link you shared
Using custom sort keys
code :
<table class="sortable">
<tr><th>Number (spelled)</th><th>Person</th></tr>
<tr><td sorttable_customkey="2">two</td><td>Jan</td></tr>
<tr><td sorttable_customkey="3">three</td><td>Bruce</td></tr>
<tr><td sorttable_customkey="1">one</td><td>Steve</td></tr>
</table>

Javascript sort numerically instead of alphabetically


By : Lawnate
Date : March 29 2020, 07:55 AM
I hope this helps you . I think this should work as expected, regardless of complexity of text ...
code :
function sort(sortableList) {
    $(sortableList).append([].slice.call($('tr', sortableList)).map(function (e) {
        return { element: e, values: ($(e).find('td').text().toUpperCase() || '').match(/([A-Z]+|\d+)/g) };
    }).sort(function (aa, bb) {
        var valuesA = aa.values ||[];
        var valuesB = bb.values ||[];
        var len = Math.min(valuesA.length, valuesB.length);
        for (var i = 0; i < len; i++) {
            var a = valuesA[i];
            var b = valuesB[i];
            if (a === b) {
                continue;
            }
            var aIsNum = !isNaN(parseInt(a));
            var bIsNum = !isNaN(parseInt(b));
            if (aIsNum && bIsNum) {
                return parseInt(a) - parseInt(b);
            }
            if (!(aIsNum && bIsNum)) {
                return a > b ? 1 : -1;
            }
            if (aIsNum) {
                return -1;
            }
            return 1;
        }
        return valuesA.length - valuesB.length;
    }).map(function (e) {
        return e.element;
    }));
    document.getElementById('msg').textContent = 'Sorted';
}
setTimeout(function () {
    return sort(document.querySelector('table'));
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="msg">Wait for it ....</span>
<table>
    <tr>
        <td>a100</td>
    </tr>
    <tr>
        <td>a10</td>
    </tr>
    <tr>
        <td>b100</td>
    </tr>
    <tr>
        <td>a20</td>
    </tr>
    <tr>
        <td>a1</td>
    </tr>
    <tr>
        <td>a2</td>
    </tr>
    <tr>
        <td style="background:red"></td>
    </tr>
    <tr>
        <td>5</td>
    </tr>
    <tr>
        <td>a</td>
    </tr>
    <tr>
        <td>b1</td>
    </tr>
</table>

How to use 'sort' in Bash to sort a two-field output numerically and alphabetically (in reverse)?


By : Brajesh Goyal
Date : March 29 2020, 07:55 AM
I wish this helpful for you Use the r for both the columns. Use 2,2 as the secondary position, you want to start sorting in column 2 and end in column 2, as well. Also, turn off locale that may change how strings are sorted.
code :
LC_COLLATE=C sort -k1,1nr -k2,2r
Related Posts Related Posts :
  • Container's height doesn't be exact as on my screen
  • How to do pagination in Google Firestore?
  • Momentjs strict format always returns 'Invalid date'
  • Is there a api or way to hook into SSRS with a MVC application
  • Can't achieve to beat a ball in my JS Pong Game
  • How do I use composition with es6 classes in the same way as this example does using factory functions?
  • Fetch local JSON file from public folder ReactJS
  • Validate form fields with javascript
  • Jquery detect click OR keystroke?
  • How to change inner div's when cloning a template?
  • Compare two objects and extract the ones that have same Key in javascript
  • Nodejs, Request and Dot notation
  • Array key does not get interpolated when making object
  • Three.js ply not showing
  • Php Ajax Form is not submitting
  • Global Variable and how pass the value in IONIC3
  • Office.js displayDialogAsync throws internal error
  • Is there a shorter way to write Ember computed/get method?
  • How can I display/hide a component depending on a property on the Redux store?
  • Range Selector - Changing bar color only when active
  • Creating a new array of objects by finding values in JSON data
  • How to avoid providing a dummy Vue data structure during initialization?
  • Digital time to readable duration using javascript
  • JavaScript update outside function variable from inner function
  • Update a document with mongoose (update property of document property)
  • Highcharts' bullet graph's serie's doesn't extend all the way
  • 2 way-binding with a nested property inside object. (VueJS + VueX)
  • Angular uiCalendar not redenring events
  • Use blade inside a JavaScript variable
  • Group objects by multiple properties in array then sum up their values
  • Electron: Maximized browserWindow overlaps Window' taskbar
  • Mongoose deep populate results in [Object] at 2nd level
  • Redux: cloning state does not work
  • angularjs detect changes in input when value is modified by JQuery
  • How to release a file after accessing it with JavaScript (adobe)
  • Handle/catch errors without repeating code?
  • Filter search Results
  • How to efficiently add items to collection with firebase firestore
  • Change Bootstrap Popover trigger on Click
  • Pushing new objects replaces previous object
  • Function with dynamic return in typescript
  • How Do I bind javascript type of File to a Nancy Model containing HttpFile?
  • Simplifying jquery / javascript for checkbox links
  • Javascript ES6 Classes composition
  • Chart.js max legend height
  • Change color of a styled checked checkbox with button
  • How to set weight and height in Css with responsive when reduce screen size
  • Price formatting and user input value to change slider
  • Pass params to q.defer (d3.csv)
  • Combine a textfield and TinyMCE field to a third field with JavaScript. Constrain TinyMCE to Numbered List
  • Javascript regex to match alpha length followed by number length
  • Pass props from child to parent react navigation
  • How to share redux store in multiple components
  • Javascript Regex Expression Not Returning Expected Value
  • with draft.js is it possible to create a custom block span with classname
  • How to convert Javascript object to a url string?
  • Adobe Javascript in Action Wizard vs a form button
  • Filtering Tooltip in Kendo
  • How to update a grouped bar-chart in d3js
  • Javascript ES6 custom sort method not working all the times
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com