array sorting based on 3 variables - javascript

I have an array with 3 types of values in which I wish to sort them.
If I only use one variable it goes all pretty well, but it all goes wrong when i want to use 3 types of variables to determine sorting order.
First variable condition: if obj.sortorder == 999999 send it to the end of the line(there is only one of this one);
if not true then
if (date < other date) put it in front of the one before
if(date > other date) put it behind the other one
if dates are equal look to sortorder to determine the order in which to apppear.
Then loop over array, reset all sortorder variables to be properly ascending in the new order.
Then splice in a new value(15th), but then it doesn't appear next to the other one, even though they have duplicate values.
My head hurts from trying to figure this one out, I just can't seem to get them in the right order.
Basically the way they are created here they should come out in the first sort. But yet the first sort is messed up with values all over the place except where I want them.
The second sort puts them miraculously in the right order but puts the 16 between the two fifteens whilst the fifteens should be next to eachother. and somehow the 24th ends up as the 9999 after the reassignment whilst the 29th should have remained as the last one.
Who can help me with this?
If you press run code snippet you get the garbled output I currently get.
The first set is what all the others should look like, except for the last one where the 15's should be hugging eachother.f
elements = [];
for (var c = 0; c < 30; c++) {
elements[c] = {
sortorder: c,
getDate: function () {
return new Date(2015, 06, this.sortorder)
}
};
}
function log(what) {
var elem = document.getElementById('sortorder');
elem.appendChild(document.createTextNode(what + "\n"));
}
for (c = 1; c < elements.length; c++) {
log(c + " = " + elements[c].getDate() + " - " + elements[c].sortorder)
}
log('--------------------------------');
elements[elements.length - 1].sortorder = 9999999;
this.elements.sort(function (one, two) {
/**
* Failsafe to prevent the last element to be placed in the middle
*/
if (one.sortorder >= 9999998) {
return 1;
}
if (two.sortorder >= 9999998) {
return -1;
}
if (one.getDate() < two.getDate()) {
return -1
}
if (two.getDate() > one.getDate()) {
return 1;
}
if (one.sortorder < two.sortorder) {
return -1;
}
if (one.sortOrder > two.sortorder) {
return 1;
}
return 0;
});
function log(what) {
var elem = document.getElementById('sortorder');
elem.appendChild(document.createTextNode(what + "\n"));
}
for (c = 1; c < elements.length; c++) {
log(c + " = " + elements[c].getDate() + " - " + elements[c].sortorder)
}
log('--------------------------------------------------------------');
elements.splice(17, 0, {
sortorder: 15,
getDate: function () {
return new Date(2015, 06, 15)
}
});
for (var c = 1; c < this.elements.length; c++) {
if (c < this.elements.length - 1) {
this.elements[c].sortorder = c;
} else {
this.elements[c].sortorder = 9999999;
}
}
for (c = 1; c < elements.length; c++) {
log(c + " = " + elements[c].getDate() + " - " + elements[c].sortorder)
}
<pre id="sortorder">
</pre>

After some experimenting, fiddling, swearing, googling, the normal process in a situation like this I finally got the solution.
I guess I was overthinking things once again.
Thanks for helping out and thinking along.
elements.sort(function(one,two)
{
var ret = 0;
/**
* Failsafe to prevent the last element to be placed in the middle
*/
if(one.sortorder >= 9999998) {
ret = 1;
}
else {
if(two.sortorder >= 9999998) {
ret = -1;
}
else {
if(one.getDate() - two.getDate() !== 0) {
ret = one.getDate() - two.getDate();
}
else {
ret = one.sortorder - two.sortorder;
}
}
}
console.log(ret);
return ret;
});

Not quite sure what you mean by "Then splice in a new value(15th), but then it doesn't appear next to the other one, even though they have duplicate values."
This does everything but that.
var last;
var newArray = [];
for(var obj in array){
obj = array[obj];
if(obj.sortorder === 999999)
last = obj;
else {
for(var item in newArray){
if(obj.date.getTime() < newArray[item].date.getTime()){
newArray.splice(item, 0, obj);
break;
}
if(obj.date.getTime() === newArray[item].date.getTime()){
if(obj.sortorder > newArray[item].sortorder){
newArray.splice(item, 0, obj);
break;
}
else{
newArray.splice(item + 1, 0, obj);
break;
}
}
}
}
}
newArray.push(last);
var sortorder = 1;
for(var item in newArray){
if(newArray[item].date.getTime() > newArray[item - 1].date.getTime())
newArray[item].sortorder = ++sortorder;
}

Related

Happy numbers - recursion

I have an issue with a recursive algorithm, that solves the problem of finding the happy numbers.
Here is the code:
function TestingFunction(number){
sumNumberContainer = new Array(0);
CheckIfNumberIsHappy(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
console.log(sumOfTheNumbers);
if(sumOfTheNumbers == 1){
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
//return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
//return false;
}
}
}
}
CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
Algorithm is working ALMOST fine. I've tested it out by calling function with different numbers, and console was displaying correct results. The problem is that I almost can't get any value from the function. There are only few cases in which I can get any value: If the number is build out of ,,0", and ,,1", for example 1000.
Because of that, I figured out, that I have problem with returning any value when the function is calling itself again.
Now I ended up with 2 results:
Returning the
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
which is giving an infinity looped number. For example when the number is happy, the function is printing in the console number one again and again...
Returning the
//return true
or
//return false
which gives me an undefined value
I'm a little bit in check by this problem, and I'm begging you guys for help.
I would take a step back and reexamine your problem with recursion in mind. The first thing you should think about with recursion is your edge cases — when can you just return a value without recursing. For happy numbers, that's the easy case where the sum of squares === 1 and the harder case where there's a cycle. So test for those and return appropriately. Only after that do you need to recurse. It can then be pretty simple:
function sumSq(num) {
/* simple helper for sums of squares */
return num.toString().split('').reduce((a, c) => c * c + a, 0)
}
function isHappy(n, seen = []) {
/* seen array keeps track of previous values so we can detect cycle */
let ss = sumSq(n)
// two edge cases -- just return
if (ss === 1) return true
if (seen.includes(ss)) return false
// not an edge case, save the value to seen, and recurse.
seen.push(ss)
return isHappy(ss, seen)
}
console.log(isHappy(23))
console.log(isHappy(22))
console.log(isHappy(7839))
Here's a simplified approach to the problem
const digits = x =>
x < 10
? [ x ]
: [ ...digits (x / 10 >> 0), x % 10 ]
const sumSquares = xs =>
xs.reduce ((acc, x) => acc + x * x, 0)
const isHappy = (x, seen = new Set) =>
x === 1
? true
: seen.has (x)
? false
: isHappy ( sumSquares (digits (x))
, seen.add (x)
)
for (let n = 1; n < 100; n = n + 1)
if (isHappy (n))
console.log ("happy", n)
// happy 1
// happy 7
// happy 10
// ...
// happy 97
The program above could be improved by using a technique called memoization
Your code is almost correct. You just forgot to return the result of the recursive call:
function TestingFunction(number){
sumNumberContainer = new Array(0);
if (CheckIfNumberIsHappy(number))
console.log(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
if(sumOfTheNumbers == 1){
return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return false;
}
}
}
}
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
for (let i=0; i<100; ++i)
TestingFunction(i.toString()); // 1 7 10 13 ... 91 94 97
I've got the solution, which was given to me in the comments, by the user: Mark_M.
I just had to use my previous
return true / return false
also I had to return the recursive statement in the function, and return the value of the CheckIfTheNumberIsHappy function, which was called in TestingFunction.
The working code:
function TestingFunction(number){
sumNumberContainer = new Array(0);
return CheckIfNumberIsHappy(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
console.log(sumOfTheNumbers);
if(sumOfTheNumbers == 1){
return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return false;
}
}
}
}
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
Thanks for the great support :)

How to find whether specific number of continuous consecutive numbers are contains in a string using javascript?

Suppose I want to know whether a string contains 5 or more continuous consecutive numbers.
var a = "ac39270982"; // False
var a = "000223344998"; // False
var a = "512345jj7"; // True - it contains 12345
var a = "aa456780"; // True - it contains 45678
Is there a RegEx available to accomplish this? Would it also be able to work in the following situation?
var a = "5111213141587"; // True
This should be true because it contains 11,12,13,14,15.
I'm not sure if it is possible to check the provided examples (single-digit, double-digit numbers) as well as larger numbers (triple-digit, etc.).
I took the time to make a 100% Javascript approach to your question. I made it to simply parse each character in the string and do integer only comparison. This works not only for five consecutive integers, but it works for checking for tenths as well (10's, 20's, etc). You can also increase/decrease the number of comparisons if you wish.
A fair warning: despite this method being potentially scalable if coded to look for all kinds of numeric sizes, you'd still be bound by computing power and number of comparisons. That is why I only provided the code for single digits and tenths, I leave it open to you/the community to decide how to expand from here.
jsFiddle
If you happen to need more details about how it works then let me know, I can further clarify its inner workings.
var str = "1111122asdgas222*&^%121314151617bdjfjahdi234bdce56789";
var consecutive = 5; // Number of comparisons
// Single digits
alert("It is " + consecutiveDigits(str, consecutive) + " that " + str + " contains " + consecutive + " consecutive digits.");
// Tenths digits
alert("It is " + consecutiveDigits(str, consecutive) + " that " + str + " contains " + consecutive + " consecutive tenths.");
function consecutiveDigits(str, consecutive){
var curr,
prev,
count = 0;
for(var i = 0; i < str.length; ++i) {
curr = parseInt(str.split('')[i]);
if(isNumeric(curr)) {
if(count === 0){
++count;
}
else if(prev + 1 === curr){
++count;
if(count === consecutive){
return true;
}
}
prev = curr;
}
}
return false;
}
function consecutiveTenths(str, consecutive, iterations){
var curr,
prev,
curr_tenth = 0,
prev_tenth = 0,
count = 0,
count_tenth = 0;
for(var i = 0; i < str.length; ++i) {
curr = parseInt(str.split('')[i]);
if(isNumeric(curr)) {
++count;
if(count === iterations){
curr_digit = (prev * 10) + curr;
alert(count_digit + " " + curr_digit + " " + prev_tenth);
if(count_digit === 0){
++count_digit;
}
else if(curr_tenth === (prev_tenth + 1)){
++count_digit;
if(count_digit === consecutive){
return true;
}
}
prev_digit = curr_digit;
count = 0;
}
else {
prev = curr;
}
}
else {
count = 0;
}
}
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
You can build regexp that will validate if it's true or not, but you might have a hard time retrieving the whole consecutive string. That said the RegExp will be a bit cumbersome, but you can create a function to create the regexp needed, depending on parameters wanted. See snippet:
function build_regexp(n) {
var string = "";
for (var i = 0; i <= 14 - n; i++) {
var start_num = i
for (var j = 0; j < n; j++) {
string += (start_num++).toString()
}
string += "|";
}
string = string.replace(/\|$/, '');
return string
}
document.getElementById('check').onclick = function() {
var regex = new RegExp(build_regexp(document.getElementById('cons').value), "g");
document.getElementById('regex').textContent = regex;
document.getElementById('result').innerHTML = (regex.exec(document.getElementById('to_check').value) || "false")
}
<div id="regex"></div>
<div>Enter wanted consecutive numbers: <input id="cons"></input></div>
<div>Enter string to check: <input id="to_check"></input></div>
<button id="check">check</button>
<div id="result"></div>
EDIT: Added a code snippet & fixed bug in numRegex
To answer the general case (i.e. contiguous sequence of arbitrary-length digits), you can do something like this:
http://jsfiddle.net/ksgLzL9u/8/
/* Find a sequence of n > 1 contiguously increasing integers in input
*
* If sequence is found, return an object:
* {
* start: <starting index of the sequence in input>,
* length: <length of the found sequence string>,
* first: <first number in the sequence>
* }
*
* Otherwise, return null
*/
function findSequence(input, n) {
var numRegex = /^(?:0|[1-9][0-9]*)$/;
// Try every starting position
for (var i = 0; i < input.length; ++i) {
// At the current starting position, try every length for the 1st number
for (var firstLen = 1; i + firstLen < input.length - 1; ++firstLen) {
var afterFirst = i + firstLen;
var first = input.slice(i, afterFirst);
// If the first string isn't an integer, move on
if (!numRegex.test(first)) {
continue;
}
// Convert the first string to an integer
var firstInt = parseInt(first, 10);
// Build what the rest of the string should look like following the
// first, in order to get a valid sequence
var rest = "";
for (var j = 1; j < n; ++j) {
rest = rest.concat(firstInt + j);
}
// Compare to what actually follows the starting string; if it
// matches, then we have our sequence; otherwise, continue on
if (input.slice(afterFirst, afterFirst + rest.length) === rest) {
return {
start: i,
length: first.length + rest.length,
first: first
};
}
}
}
return null;
}
$(function() {
function processChange() {
var input = $('#input').val();
var n = parseInt($('#n').val());
if (n > 1 && input.length) {
var result = findSequence(input, n);
if (result) {
$('#result').text(JSON.stringify(result, null, 2));
var afterFirst = result.start + result.first.length;
var afterSeq = result.start + result.length;
$('#highlighted').empty()
.append($('<span/>')
.text(input.slice(0, result.start)))
.append($('<span/>')
.addClass('sequence')
.append($('<span/>')
.addClass('first')
.text(result.first))
.append($('<span/>')
.text(input.slice(afterFirst, afterSeq))))
.append($('<span/>')
.text(input.slice(afterSeq)));
} else {
$('#result').text("No sequence found");
$('#highlighted').empty();
}
} else {
$('#result').text("");
$('#highlighted').empty();
}
}
$('input,n').on("keyup mouseup", processChange);
processChange();
});
#input {
width: 50%;
min-width: 200px;
}
#n {
width: 50px;
}
.highlighted-result {
font-family: monospace;
}
.highlighted-result .sequence {
background-color: yellow;
}
.highlighted-result .first {
border: solid black 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h1>Input</h1>
<div>
<input id="input" type="text" value="111121314155" placeholder="input">
<input id="n" type="number" value="5" placeholder="n">
</div>
<h1>Results</h1>
<div id="highlighted" class="highlighted-result"></div>
<pre id="result"></pre>
I haven't attempted to optimize the solution (e.g. the firstLen iteration can be short-circuited, and the entire rest string doesn't need to be built up), but I left as-is to make the algorithm clearer.
function NstreamsOfNumberN (str) {
for (let i = 0; i < str.length; i++) {
let numBeingConsidered = Number(str[i]);
let numOfComparisonsToBeDone = numBeingConsidered - 1;
for (let j = i; j < numOfComparisonsToBeDone + i; j++) {
if (str[j] != str[j+1]) {break}//compare neigbourin nums
else if ((j - i + 1) === numOfComparisonsToBeDone)
{ let theNwithNstreams = numBeingConsidered
return [str, (theNwithNstreams), true]}
//(j - i + 1) equals num of comparisons that has been done.
}
}
return [str,null,false]
}
NstreamsOfNumberN('334775555583444582')
9 streams of the number 9
8 streams of the number 8
7 streams of the number 7 ...
3 streams of the number 3
2 streams of the number 2.
It is very difficult to do this with regex, but here is a tentative:
One digit
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4,}\d
https://regex101.com/r/mw4bvG/1
Two digits
(?:(\d)(?:0(?=(?:\1)1)|1(?=(?:\1)2)|2(?=(?:\1)3)|3(?=(?:\1)4)|4(?=(?:\1)5)|5(?=(?:\1)6)|6(?=(?:\1)7)|7(?=(?:\1)8)|8(?=(?:\1)9))|09(?=10)|19(?=20)|29(?=30)|39(?=40)|49(?=50)|59(?=60)|69(?=70)|79(?=80)|89(?=90)){4,}\d{2}
https://regex101.com/r/Kcl9FC/1
Three digits
(?:(\d{2})(?:0(?=(?:\1)1)|1(?=(?:\1)2)|2(?=(?:\1)3)|3(?=(?:\1)4)|4(?=(?:\1)5)|5(?=(?:\1)6)|6(?=(?:\1)7)|7(?=(?:\1)8)|8(?=(?:\1)9))|(\d)(?:09(?=(?:\2)10)|19(?=(?:\2)20)|29(?=(?:\2)30)|39(?=(?:\2)40)|49(?=(?:\2)50)|59(?=(?:\2)60)|69(?=(?:\2)70)|79(?=(?:\2)80)|89(?=(?:\2)90))|099(?=100)|199(?=200)|299(?=300)|399(?=400)|499(?=500)|599(?=600)|699(?=700)|799(?=800)|899(?=900)){4,}\d{3}
https://regex101.com/r/joeWdR/1
All together
(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4,}\d|(?:(\d)(?:0(?=(?:\1)1)|1(?=(?:\1)2)|2(?=(?:\1)3)|3(?=(?:\1)4)|4(?=(?:\1)5)|5(?=(?:\1)6)|6(?=(?:\1)7)|7(?=(?:\1)8)|8(?=(?:\1)9))|09(?=10)|19(?=20)|29(?=30)|39(?=40)|49(?=50)|59(?=60)|69(?=70)|79(?=80)|89(?=90)){4,}\d{2}|(?:(\d{2})(?:0(?=(?:\2)1)|1(?=(?:\2)2)|2(?=(?:\2)3)|3(?=(?:\2)4)|4(?=(?:\2)5)|5(?=(?:\2)6)|6(?=(?:\2)7)|7(?=(?:\2)8)|8(?=(?:\2)9))|(\d)(?:09(?=(?:\3)10)|19(?=(?:\3)20)|29(?=(?:\3)30)|39(?=(?:\3)40)|49(?=(?:\3)50)|59(?=(?:\3)60)|69(?=(?:\3)70)|79(?=(?:\3)80)|89(?=(?:\3)90))|099(?=100)|199(?=200)|299(?=300)|399(?=400)|499(?=500)|599(?=600)|699(?=700)|799(?=800)|899(?=900)){4,}\d{3}
https://regex101.com/r/NyCLh6/1

javascript recursion counter

I tried to rewrite this indexOf MDN example to practice recursion
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
This was my solution:
var count = 0;
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return count;
}
else {
count ++;
return countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
It works, but is there anyway to get the count variable inside the function itself? Is it not really a true recursion if I have a count variable outside the function?
In a recursive function, if you want to keep a variable around from one "iteration" to the next, then you need to pass it as an argument:
function countLetters(str, p, count) {
count = count || 0;
var pos = str.indexOf(p);
if (pos == -1) {
return count;
}
else {
return countLetters(str.substr(pos + 1), p, count + 1);
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
// => 4
However, this is not always necessary, as Arun P Johny's answer illustrates.
What you can do is to return the count value form the method, so if the item is not found you return 0, else you return 1 + value-of-recursive-call
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return 0;
} else {
return 1 + countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
Demo: Fiddle

function to check if the element at given position in given array of integers is bigger than its two neigbours

I am adding my question here as well as in the title:
function to check if the element at given position in given array of integers is bigger than its two neighbours.
Here is my sample code:
`var dTest = new Array();
dTest[0] = 1;
dTest[1] = 2;
dTest[2] = 3;
dTest[3] = 4;
dTest[4] = 5;
for (i=0;i<11;i++){
if(dTest[i]>dTest[i+1] && dTest[i]>[i-1])
{
console.log("");
}
else
{
console.log("");
}
};`
So what I am trying is written in the tittle. Thx :)
Well for starters, for some reason your for loop is going until 11 (magic number? why 11, it makes no sense). Change your loop to run for the length of the array, then check to see if a number even exists to the "left" or "right", if so, then do logic:
for (var i = 0; i < dTest.length; i++) {
if (dTest[i-1] != undefined && dTest[i+1] != undefined) {
//this position has neighbors!
var current = dTest[i];
if (current > dTest[i-1] && current > dTest[i+1]) {
console.log(current + " is bigger than it's neighbors!");
} else {
console.log(current + " is smaller than it's neighbors!");
}
} else {
console.log(dTest[i] + " doesn't have enough neighbors!");
}
}
Demo: http://jsfiddle.net/NFHTg/
You have a problem with checking indexes in your array that don't exist. This solution should fix it:
for (var i = 0; i < dTest.length; i++) {
if ((dTest[i-1] != undefined && dTest[i-1] > dTest[i]) ||
(dTest[i+1] != undefined && dTest[i+1] > dTest[i])) {
console.log('Element at position ' + i + ' is not bigger than his neighbours');
} else {
console.log('Element at position ' + i + ' is bigger than his neighbours');
}
}

sorting an alphanum array using jQuery

i am trying to compare two arrays containing alphabets and numbers using jquery but a call to the function does nothing.
jQuery.compare = function (string2,string1) {
alert("comparing")
var i, j;
for ( i = 0, j=0; i < string2.length|| j<string1.length; ++i,++j) {
var n1 = 0,n2=0;
if ($.isNumeric(string2[i+1])) {
num=string2[i]
while ($.isNumeric(string2[i+1])) {
i++;
num += string2[i]
}
n1 = 1;
}
if ($.isNumeric(strin1[j])) {
num1 = string1[j]
while ($.isNumeric(string1[j+1])) {
j++;
num1 += string1[j]
}
n2 = 1;
}
if (n1 == 1) {
if (n2 = 1) {
if( parseInt(num1) - parseInt(num) !=0)
return parseInt(num1) - parseInt(num);
}
else
return 1;
}
else if (n2 = 1)
return -1;
else {
if(string2[i]-string1[j]!=0)
return string2[i]-string1[j]!=0;
}
}
if (j < string1.length)
return -1;
else
return 1;
}
Also i would like to know the best way to call this function. I would like to use something like string1.compare(string2) and replace string1 with 'this' in the above code fragment.
EDIT:
This is how i call the compare function.Here, colValues is an array of string.
$.fn.sort = function (colValues) {
alert("sorting")
var i;
for (i = 0; i < colValues.length; ++i) {
for (var j = 0; j < i - 1; ++j) {
alert("before compare")
if(colValues.compare(colValues[j],colValues[j + 1])) {
var temp = colValues[j];
colValues[j] = colValues[j + 1];
colValues[j + 1] = temp;
}
}
}
return colValues
}
if i replace
if(colValues.compare(colValues[j],colValues[j + 1]))
with
if(colValues[j]>colValues[j+1])
my sort function works.
i am a complete newbie at coding in jquery. There is probably some syntactical error. I dont really want any help with the algorithm just the syntax.
jsfiddle-checkout my code here
EDIT2:
i fixed everything thx to metadings.
heres what i had to change
1)
jQuery.compare
to
$.fn.compare
2)
if($.isNumeric(string2[i+1]))
to
if(jQuery.isNumeric(string2[i + 1]))
somehow the
while ($.isNumeric(string1[j+1]))
syntax worked without any changes
3)
parseInt(num1) - parseInt(num)
didnt work either as it returned NaN. To solve this problem i defined two var variables 'number1' and 'number2' and initialized them with 0's and assigned parseInt(num1) individually to the variables and then subtracted the new variables.

Categories

Resources