logo
down
shadow

Array not sorting correctly in javascript


Array not sorting correctly in javascript

By : Bayern
Date : November 22 2020, 02:59 PM
To fix the issue you can do In alphabetical sort, it just looks at the characters sequentially so "E10N1" would be before "E10N9", even though there is another character after the "E10N1". Just like "abcd" comes before "abd".
If you really want the type of sort you're asking for, it is going to take a much more complicated custom sort algorithm that actually parses the numeric parts of the tag to do actual numeric comparisons (not alphabetic sorts) on them.
code :
var array = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5", "E10N8", "E10N6", "E10N7"];

var regex = /\d+$/;
function getLastNum(str) {
    var m = str.match(regex);
    if (m) {
        return parseInt(m[0], 10);
    } else {
        return -1;
    }
}

array.sort(function(a, b) {
    return getLastNum(a) - getLastNum(b);
});
document.write(JSON.stringify(array));
Get the next character of each string
If not both digits, then compare the characters directly and return the result
If both digits, then collect sequence of digits in both strings
    Longest sequence of consecutive digits is higher
    While accumulating sequential digits, keep track of which sequence
       has the first non-equal digit that is higher than the other
    If sequences were the same length, then the previous collected value  
       of which sequence had the first different higher number determines
       which sequence comes first
If sequence of digits or single character were equal, go to next character
    and start the above process over
var array = ["E10N1", "E10N3", "E10N10", "E10N2", "E10N4", "E10N9", "E10N5", 
   "E10N8", "E10N6", "E10N7", "C10N1", "D10N3", "E11N10", "E09N2", "E999N4",
   "E10000N9", "g10N6", "z10N6", "q10N6", "R10N6", "E001N1", "E00N1",
   "E0000N1", "zN1", "zN000", "zN00", "000", "00", "0001", "0002", "A00",
   "A", "0A"];
// return negative value if a < b
// return 0 if a === b
// return positive value if a > b
// 
// Rules:
// - Sort characters before numbers
// - Ignore leading zeroes on digits
// - Ignore plus/minus signs in front of digits
// - For sequences of zeroes the shorter sequence is first
//
function alphaNumCompare(a, b) {
    var aIndex = 0,
        bIndex = 0,
        aChar, bChar, result;

    function isDigit(ch) {
        return ch >= "0" && ch <= "9";
    }

    function compareNums() {
        // aChar, bChar contain first digit
        // get rest of consecutive digits and compare
        // returns negative, 0 or positive
        // as side affect, advances aIndex and bIndex to next non-numeric
        var aZeroLen = 0,
            bZeroLen = 0,
            aNumStr = "",
            bNumStr = "";
        // collect consecutive digits from a and b
        // ignore any leading zeroes
        if (aChar === "0") {
            ++aZeroLen;
        } else {
            aNumStr = aChar;
        }
        if (bChar === "0") {
            ++bZeroLen;
        } else {
            bNumStr = bChar;
        }
        while (aIndex < a.length) {
            aChar = a.charAt(aIndex);
            if (!isDigit(aChar)) {
                break;
            }
            ++aIndex;
            // don't add leading zeroes and keep a count of leading zeroes
            if (aChar === "0" && aNumStr === "") {
                ++aZeroLen;
            } else {
                aNumStr += aChar;
            }
        }
        while (bIndex < b.length) {
            bChar = b.charAt(bIndex);
            if (!isDigit(bChar)) {
                break;
            }
            ++bIndex;
            // don't add leading zeroes and keep a count of leading zeroes
            if (bChar === "0" && bNumStr === "") {
                ++bZeroLen;
            } else {
                bNumStr += bChar;
            }
        }
        // we now have a series of consecutive digits in aNumStr and bNumStr
        if (aNumStr.length === bNumStr.length) {
            // check for nothing but leading zeroes in both
            if (aNumStr.length === 0) {
                return aZeroLen - bZeroLen;
            }
            if (aNumStr === bNumStr) {
                return 0;
            } else {
                return aNumStr < bNumStr ? -1 : 1;
            }
        } else {
            // lengths are not equal, then shorter string comes first
            return aNumStr.length - bNumStr.length;
        }
    }
    // loop while both strings have characters left
    while (aIndex < a.length && bIndex < b.length) {
        aChar = a.charAt(aIndex++);
        bChar = b.charAt(bIndex++);
        if (isDigit(aChar) && isDigit(bChar)) {
            result = compareNums();
            if (result !== 0) {
                return result;
            }
        } else {
            // not both numeric, just compare the characters themselves
            result = aChar.localeCompare(bChar);
            if (result !== 0) {
                return result;
            }
        }
    }
    // shorter one is first
    return (a.length - aIndex) - (b.length - bIndex);
}

array.sort(alphaNumCompare);
document.write(JSON.stringify(array).replace(/,/g, ", "));


Share : facebook icon twitter icon
Javascript not sorting DECIMAL numbers correctly

Javascript not sorting DECIMAL numbers correctly


By : Neenu Varghese
Date : March 29 2020, 07:55 AM
I hope this helps . Think the problem is that you need to sort by the value as well but you are only sorting by the name.
The below should fix it, it sorts alphabetically and then numerically.
code :
function(x, y) {
    var parts = {
        x: x.myname.split(' - '),
        y: y.myname.split(' - ')
    };
    if (parts.x[0] == parts.y[0]) // strings are the same
        return parseFloat(parts.x[1]) - parseFloat(parts.y[1]); // sort by number
    return parts.x[0] > parts.y[0] ? 1 : -1; // sort by string
}
Resort array of objects on another key without disturbing previous sorting (part-sorting) in JavaScript

Resort array of objects on another key without disturbing previous sorting (part-sorting) in JavaScript


By : user2220000
Date : March 29 2020, 07:55 AM
With these it helps Assuming that you already have bookArray sorted by Rate. It can be sorted on second level using following. Can be fine tuned better for easy usability.
code :
var arr = bookArray;
var firstSortKey = 'Rate';
var secondSortKey = 'Name';
var count = 0 ;
var firstSortValue = arr[count][firstSortKey];

for(var i=count+1; i<arr.length; i++){
     if(arr[i][firstSortKey]!==firstSortValue){
         var data = arr.slice(count, i);
         data = data.sort(function(a, b){
             return a[secondSortKey]>b[secondSortKey];
         });
         var argsArray = [count, i-count];
         argsArray.push.apply(argsArray, data);
         Array.prototype.splice.apply(arr, argsArray);
         count = i;
         firstSortValue =  arr[i][firstSortKey];
     }
}
Javascript Sort not sorting correctly

Javascript Sort not sorting correctly


By : Jeremy Mange
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further The reason you're getting these results is that your sort is not numeric, it is based upon canonical values of the numbers.
The reason why 21.35 comes after number 102.35 is because the digit 1 in 102.35 is smaller than the digit 2 in 21.35 and 0 in 200 is smaller than 1 in 21.35.
code :
var numericallyOrderedDivs = $divs.sort(function (a, b) {
    return parseFloat($(a).find("h2").text()) > parseFloat($(b).find("h2").text());
});
After sorting an array of objects in JavaScript, how would I display the opposite way of sorting? (update)

After sorting an array of objects in JavaScript, how would I display the opposite way of sorting? (update)


By : kevin castillo
Date : March 29 2020, 07:55 AM
seems to work fine To reverse the order of a sorted array use Array#reverse - tableIn.revese().
To sort in the opposite direction, multiply the result of your sortAsc function by -1.
code :
var question1 = "name";

function sortAsc(x, y) {
    if (question1 == "name") {
      var ayy = x.name.toLowerCase();
      var byy = y.name.toLowerCase();
      if (ayy < byy) {
        return -1;
      }
      if (ayy > byy) {
        return 1;
      }
      return 0;
    } else {
      return x.itemsBought - y.itemsBought;
    }
}

function sortFunc(x, y) {
  var factor = question2 == "up" ? 1 : -1;
  return  factor * sortAsc(x, y);
}

var tableIn = [
  {name: "Alaska Thunder", itemsBought: 15},
  {name: "Courtney Act", itemsBought: 20},
  {name: "Bianca del Rio", itemsBought: 13}
];

var question2 = "up";
console.log('sortAsc: ', tableIn.sort(sortFunc));

var question2 = "down";
console.log('sortDesc: ', tableIn.sort(sortFunc));
Javascript: Sorting an array of objects based on a timestamp property doesn't sort one element correctly

Javascript: Sorting an array of objects based on a timestamp property doesn't sort one element correctly


By : thotp
Date : March 29 2020, 07:55 AM
should help you out The JS .sort function requires a comparator that returns a negative number, zero, or a positive number. Your second returns a boolean.
Your first function fails because you do (a < b) ? 1 : (b > a) ? -1 : 0, but the two comparisons are equivalent, i.e. you got the second comparison the wrong way around.
code :
.sort((a, b) => +a[1].currentStatusTimestamp - +b[1].currentStatusTimestamp);
Related Posts Related Posts :
  • Why is my jquery code not working or throwing any errors?
  • Javascript/jquery - Wrap text with tag at specific position
  • Javascript Canvas can't draw multiple curves
  • Javascript move entire span with arrow keys
  • How to stop my character from going outside the div?
  • How to call in plugin options in jquery plugins
  • Remove default submit on modal form button
  • Generate angular model properties by view, when view fields are empty
  • AngularJS - project files layout, injection and scope clarification
  • get text fields that are not empty
  • Jasmine Async Callback Timeout
  • Attach jQuery inputmask to DOM element
  • Error when checking checkbox property
  • JWPlayer 7 error on setup function not working
  • Chaining async Promises with 1 resolve and 1 reject?
  • Create websocket server to send/receive complex objects using SuperWebSocket
  • Pass variable from php to javascript function argument
  • How to update ng-repeat after POST of new items to server
  • How to use firebase-tools as a module and to deal with promises
  • How to get Factorial of number in JavaScript?
  • how to iterate html elements and swap their values
  • backbone router several root, how to load this properly?
  • 2 Validators Only 1 throwing catchable isvalid error
  • Prevent ng-include content from pre-loading until toggled to show
  • D3: Set filter flood-color based on data
  • Jquery autocomplete not a function
  • Highcharts wrong size on window maximize
  • Why these minified comments in JS don't break the code?
  • Angular $q not working as expected - returning undefined
  • Unable to click or submit button using selenium webdriver js
  • Is it possible to make request between two domains?
  • angularjs dynamically change footer
  • Issue attaching javascript events using variation on module pattern
  • Resize a CSS div box dynamically
  • Add one day to User-Input Day using Javascript in a PDF
  • Change contents of div, on <a> click
  • Waiting for function with a setTimeout to complete without tampering with that function
  • JqueryUI (Ajax) Hide() works, Show() does not
  • Nodejs, Express + Angular POST 404
  • Most performance optimal foreach function with getting index
  • How to add live search to Rails 4.2?
  • Why my jQuery function getJSON is not calling my function callback?
  • Passing more parameters into callback function
  • Should.js chaining multiple assertions on a single property
  • Buttons/toggles not working in jquery
  • Smooth scrolling workaround
  • Date math works on Chrome but not on Firefox or Safari
  • Google Analytics in AngularJS. Cannot see real-time page viewing
  • Smooth canvas line and on curser start point
  • RequireJS not loading createjs
  • Highcharts tooltip bug with stacked column chart
  • Javascript - UTC date to local date
  • ngMock complains unexpected request when request is expected
  • Angular get offset of element by id
  • Validate date with jquery and help user
  • How to start with javascript code obfuscation? Not looking for tools
  • Click doesn't work on this Google Translate button?
  • Vue.js: Using prerendered html as template for parent and child components
  • Bind to model from child directive where model has not been resolved at compile-time
  • How i can get twitter count now?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co