sort table alphanumerically with js - javascript

I'm trying to modify sorttable.js to add the option to sort alphanumerically.
Right now, if you sort by alpha, strings with numbers in them will sort like this:
String 1
String 10
String 100
String 2
If I make it sort numeric, it ignores the alpha characters when sorting. I'm trying to figure out how to combine the two functions to make it sort by both at once. Here are the two functions:
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
Could anybody provide any pointers on how I might begin?

in you function, get the 2 numbers. convert them to strings. figure out which is the longest. add "leading zeros" to the other one, then sort alpha as usual.

Related

Sort a list by the second number after a dot

I need to sort a list by the second batch number with JavaScript.
This is how it looks like now:
1101.19
1201.17
1301.09
What I need is:
1301.09
1201.17
1101.19
As I am still learning to program I can't figure out the issue. But need it at work.
Can someone help me understand the process of how to do it?
Sort the array depending on the decimal part. Here is the solution
Sort the array by selecting the decimal part of the number inside the sort function.
You can get the decimal part of any number by taking modulus operation with 0.1. Link.
const arr = [1101.19, 1201.17, 1301.09, 1201.20];
arr.sort((a, b) => {return (a % 1 - b % 1)});
console.log(arr);
You need to split each element before sort and compare second parts
let array = ["1101.69", "1701.57", "1301.09"];
array.sort((a,b)=>{
let pair1 = a.split('.');
let pair2 = b.split('.');
return ( parseInt(pair1[1]) < parseInt(pair2[1])) ? -1 : 1;
});
console.log(array);

continually add values in javascript with while loop

I'm a newbie to Javascript so please bear with me for this basic question,
I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!
3253611569939992595156
113 // result of the above digits all added together
5 //result of 1+1+3
I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!
function rootFunc(n) {
var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number
while (splite.length > 1) {
splite = splite.reduce(getSum);
}
return splite;
}
console.log(rootFunc(325361156993999259515));
function getSum(total, num) {
return total + num;
}
You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:
function digits(n) {
return n.toString().split('').map(x =>Number(x));
}
Then split each time:
function rootFunc(n) {
var d = digits(n);
while (d.length > 1) {
d = digits(d.reduce(getSum));
}
return d;
}
The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :
if(splite > 9) splite = rootFunc(splite);
This way, you check if the result is greater than 10, if not you do the function with the remaining digits
I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block:
splite = splite.toString().split('').map(x =>Number(x));

How can I find the sum of each individual element in an array of long numbers? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This question will need to be answered in Javascript.
For example, I have an array of phone numbers:
var phoneNumbers = ['123-434-4455', '123-495-8475', '484-728-3456'];
The phone number at index 0 (123-434-4455) would be added as 1+2+3+4+3+4+4+4+5+5, totaling to 35.
I'm guessing this will involve some kind of loop (for loops, or the method .forEach), because I will need to do this for multiple phone numbers in an array that will probably be randomly generated by a computer, so length and amount will vary.
Also, I'm wondering if the hyphen will matter, in which case I have found .replaceAll("-","");.
I've researched some other methods on here that involve .split, .parsInt, .map, .toString, .reduce, .digitSum, and more. They seem pretty complicated, especially since I'm in a beginning course (however I'm totally new to programming - this is my first post btw). Also, I'd rather not post the full question because I really want to figure it out alone, but this is the part I'm most stuck on. Forgive me if this has been answered previously! Like I said...new to programming.
I also need to determine which phone number has the last largest sum of digits, and use a return statement to return the required phone number in its’ original form.
You can use map and reduce array methods:
['123-434-4455', '123-495-8475', '484-728-3456'].map(function(str) {
return str.split('').reduce(function(a,b) {
return a + (+b || 0);
}, 0);
}); // [ 35, 48, 51 ]
Some notes:
split('') splits a string into an array of characters
+b coerces b into a number, e.g. "5" to 5 and "-" to NaN.
+b || 0 will return 0 if +b is falsy (0 or NaN), and +b otherwise
This code will do it:
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i<phoneNumbers.length; i++) {//For every phone number
var total=0; //create a total variable
var indNumbers = phoneNumbers[i].replace(/-/g, ""); //remove all dashes
for (var j=0; j<indNumbers.length; j++) {//loop for all digits
total+=parseFloat(indNumbers[j]);//add each digit to total
}
console.log(total);//do stuff with it here
}
All pretty standard javascript stuff. Only confusing bit I might have used is the .replace method - my parameter is /-/g which might look scary, but it's the equivalent of passing in "-" except it tells the function to replace ALL instances of the dash. If you do pass "-", it only replaces the first instance.
If you're a beginner, the things in this code you'll want to learn about are .replace, parseFloat for loops, and accessing strings using square bracket notation.
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
function crossSum(arr, pos) {
var sum = 0;
var a = arr[pos].split("-").join("").split("");
a.forEach(function(e, i) {
sum += parseInt(a[i]);
})
return sum;
}
document.write(crossSum(phoneNumbers, 0));
This function will return the cross-sum of
your phone-number.
Just use crossSum(phoneNumers, 0) // 0 is the fist number of phoneNumbers.
This will return the crossSum.
Adding on #millerbr answer. If you don't want to use .replace you can just use parseInt/parseFloat on every char, if it is not a number those functions returns NaN which can be checked with isNaN() function
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i < phoneNumbers.length; i++) { //For every phone number
var total=0; //create a total variable
for (var j=0; j < phoneNumbers.length; j++) { //loop for all digits
var parsedNumber = parseInt(phoneNumbers[j]); // parse string to number or NaN if "-"
if (!isNaN(parsedNumber)) { // Check if result is NaN (Not a Number).
total += parsedNumber; //add each digit to total
}
}
console.log(total);//do stuff with it here
}
Assuming that phoneNumbers is an array of strings, you can indeed loop through the entire array and then in each element in the array you can loop through the string and check if the character is a number. If so, add it to your sum and then when you finish each element in the array you have the total sum for it and you can add it to another array full of your sums.

Sorting Javascript array with strings and numbers

I have a list of elements in an array in Javascript as follows:
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB",...]
and so on. I would like to sort the array on the freespace, so in the example above Datastore two would be the first element in the array. The array is always constructed with "- free space xx.xxGB", but the free space could be 5 digits in some cases, so xxx.xxGB for example.
Can anyone help provide a way of sorting the array please? I see I can use something like
"*- free space\s[1-9][0-9]*GB"
So would this be like
myArray.sort("*- free space\s[1-9][0-9]*GB") ?
Is this correct or how would I do this? Many thanks in advance.
Pull the numeric parts out in a custom sort function, and subtract:
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore three - free space 6.23GB" ];
var re = /([0-9\.]+)GB/; // regex to retrieve the GB values
myArray = myArray.sort(
function(a, b) {
var ma = a.match(re); // grab GB value from each string
var mb = b.match(re); // the result is an array, with the number at pos [1]
return (ma[1] - mb[1]);
}
);
alert(myArray.join("\r\n"));
This should do the trick:
myArray.sort(function compare(a, b) {
var size1 = parseFloat(a.replace(/[^0-9\.]/g, ''));
var size2 = parseFloat(b.replace(/[^0-9\.]/g, ''));
if (size1 < size2) {
return -1;
} else if (size1 > size2) {
return 1;
}
return 0;
});
Array.prototype.sort does not accept a regex, it accepts a callback or will do its best to sort your array based on numeric/alphabetical order if you don't pass a callback
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
This should work as well if you just want the numbers returned.
I split the string by spaces and grab the last section. (#GB), I then grab the substring of everything but the last two characters (so I chop off the GB), I then use the Javascript function to sort the remaining numbers.
JSFiddle Demo
window.onload = function() {
myArray = ["Datastore one - free space 34.23GB", "Datastore two - free space 56.23GB", "Datastore two - free space 16.23GB", "Datastore two - free space 6.23GB"];
for (i = 0; i < myArray.length; i++)
{
var output = myArray[i].split(" ").pop();
output = output.substring(0, output.length-2);
myArray[i] = output;
}
myArray.sort(function(a, b){return a-b});
alert(myArray);
};

jquery Tablesorter - natural sort order?

I've looked through all the answers listed for tablesorter but can't find what I'm looking for.
I have a table which I'm trying to sort, one column contains product model numbers which include both letters and numbers, the problem is that it sorts alphabetically but not with the numbers in their proper order. For example the sorted column comes out like this:
STRB 18,
STRB 19,
STRB 2,
STRB 20,
STRB 23 - you get the idea.
I've gathered that I need this column to sort in natural order, but I've not got any js chops to do this with. If anybody could point me in the right direction I would be very grateful!
taken from some old code of mine
compare = {
natural: function(a, b) {
function prepare(s) {
var q = [];
s.replace(/(\D)|(\d+)/g, function($0, $1, $2) {
q.push($1 ? 1 : 2);
q.push($1 ? $1.charCodeAt(0) : Number($2) + 1)
});
q.push(0);
return q;
}
var aa = prepare(a), bb = prepare(b), i = 0;
do {
if(aa[i] != bb[i])
return aa[i] - bb[i];
} while(aa[i++] > 0);
return 0;
}
}
example of use
test = ['img100b', 'img21', 'img18', 'img100a', 'img1', 'img2']
console.log(test.sort(compare.natural))
The jquery tablesorter plugin offers the ability to write your own parser.
Check out the example and give it a shot!
http://tablesorter.com/docs/example-parsers.html
Not sure what you mean by "natrual" order, but I am guessing you mean that strb 2 would be before strb 18.
The order you have above is correct for strings. if you want to sort by the number portion (assuming all the strb's are always the same) you will have to do a substring to get the number only and then sort the data.
I would also NOT do this in javascript. Let your database work for you and let it handle the order of the data. It will save you a lot of pain.

Categories