I am having difficulty getting this sort to work.
Current always has precedence over name.
I can get it to sort on the values of either current or name but not both.
My array look like this.
var arr = [{current:true, name:"A name"},
{name:"A name"}, {name:"B name"},
{current:true, name:"B name"}];
arr.sort(sort_me)
Here's the sort function.
var sort_me = function(left, right){
var value = "name";
var sort_by_val = function(){
return left[value] == right[value] ? 0 : (left[value] < right[value] ? -1 : 1);
}
if(left.current===right.current) {
sort_by_val();
}else{
if(left.current===true){
return -1;
}else{
if(right.current===true){
return 1;
}else{
sort_by_val();
}
}
}
}
You're missing a return:
if(left.current===right.current) {
return sort_by_val();
}
Otherwise your return value will be undefined if both currents are set:
var sort_me = function(left, right){
var nameorder = left.name === right.name ? 0 : (left.name < right.name ? -1 : 1);
if(
(left.current && right.current) ||
(!left.current && !right.current)
) {
return nameorder;
} else if(left.current) {
return -1;
} else {
return 1;
}
}
Try
var sort_me = function(left, right) {
var value = "name";
var sort_by_val = function() {
return left[value] == right[value] ? 0 : (left[value] < right[value]
? -1
: 1);
}
if (left.current === right.current) {
return sort_by_val(); //missing return
} else {
if (left.current === true) {
return -1;
} else if (right.current === true) {
return 1;
} else {
return sort_by_val(); //missing return
}
}
}
Demo: Fiddle
Related
Hey guys i have a hard time in understanding multiple ternary conditions. Here is my code below
<div
className={
this.state.currentIndex == index
? "question-box bg-red-box"
: question.visited
? question.review
? "question-box review-box"
: question.selected_answer == null
? "question-box white-box"
: "question-box orange-box"
: "question-box"
}
>
How can i write this in if else (just for understanding). I know the conditions here would not be understable but just i want it in if else to get a clear understanding
Thanks !
The direct translation into if/else would be:
let temp;
if (this.state.currentIndex == index) {
temp = "question-box bg-red-box"
} else {
if (question.visited) {
if (question.review) {
temp = "question-box review-box";
} else {
if (question.selected_answer == null) {
temp = "question-box white-box"
} else {
temp = "question-box orange-box"
}
}
} else {
temp = "question-box"
}
}
// later:
<div className={temp} />
Neither version of the code is easy to understand. I would probably do something like the following instead:
let highlight = '';
if (this.state.currentIndex === index) {
highlight = "bg-red-box";
} else if (question.visited && question.review) {
highlight = "review-box";
} else if (question.visited && question.selected_answer === null) {
highlight = "white-box";
} else if (question.visited) {
highlight = "orange-box";
}
// ...
<div className={`question-box ${highlight}`} />
let currentIndex = 1;
let index = 2;
let question = {
visited: true,
review: false,
selected_answer: null
}
let output = '';
if(currentIndex == index){
output = 'question-box bg-red-box'
} else if (question.visited) {
if(question.review){
output = "question-box review-box"
} else if (question.selected_answer == null) {
output = "question-box white-box"
} else {
output = "question-box orange-box"
}
} else {
output = "question-box"
}
console.log(output)
I am sorting on the basis of doc_status the items using sort function.
Everything is fine just one case when doc_requirment =0 I want it to be last element of items irrespective of its doc_status.
var lockStatus = 2;
var items = [
{ doc_requirement :4, doc_status :0 },
{ doc_requirement: 3,doc_status:1 },
{ doc_requirement:0,doc_status :2},
{doc_requirement: 3 ,doc_status :3},
{ doc_requirement: 1,doc_status : 0},
];
if(lockStatus == 2){
var finalSortedDocuments = items.sort(function(firstDoc,secondDoc){
var order = [2,0,1,3];
if(firstDoc.doc_status == secondDoc.doc_status && firstDoc.doc_status ==0){
var orderNew = [ 1,4];
return orderNew.indexOf(firstDoc.doc_requirement) - orderNew.indexOf(secondDoc.doc_requirement);
}
return order.indexOf(firstDoc.doc_status) - order.indexOf(secondDoc.doc_status);
});
}
You just have to add one more criteria to the sorting function:
items.sort(function(firstDoc, secondDoc) {
if(firstDoc.doc_requirement == 0 && secondDoc.doc_requirement != 0) return 1;
else if(firstDoc.doc_requirement != 0 && secondDoc.doc_requirement == 0) return -1;
// Then sort by doc_status
var order = [2,0,1,3];
return (order.indexOf(firstDoc.doc_status) - order.indexOf(secondDoc.doc_status));
});
Try something like this-
items.sort(function(doc1,doc2){
if(doc1.doc_requirement=== 0){
return 1;
}
if(doc2.doc_requirement=== 0){
return -1;
}
return doc1.doc_status > doc2.doc_status;
})
You can try like this
var finalSortedDocuments = items.sort(function(firstDoc,secondDoc){
if(firstDoc.doc_status== 0){
return(1);
}
if(secondDoc.doc_status== 0){
return(-1);
}
return firstDoc.doc_status-secondDoc.doc_status;
});
I am trying like this:
function k(){
var x = $('#textArea').val();
for (i = 0; i < x.length; i++)
{
if(x[i].match(/^[0-9]/))
{
if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
{
if(x[i+11].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
{
if(x[i+9].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
return 'true';
}
Or simply
var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
Or if you only want to allow - and digits
var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length )
{
return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
or using pure regexp
to match the 123-45-678 and 12345678 formats:
var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
return true;
} else return false;
to match any number less then 9 digits:
var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
return true;
} else return false;
I am writing a function that will return an array with prime numbers.
The function should return an array with n elements. (n is a parameter) But it returns only one element. Why?
My codes:
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
else if (res == 0 && initNum == currCompose)
{
arr[currIndex] = initNum;
++currIndex;
break;
}
else if (res != 0 && initNum != currCompose)
{
continue;
}
else
{
console.log("Impossible result!");
}
}
}
return arr;
}
findPrimes(2); //return 2
findPrimes(10); //return 2 too
Jsbin
You should not be comparing initNum to currCompose. Keep in mind that initNum is the number you are checking (say, 71), and currCompose will be at most ceil(sqrt(initNum)) (say 9), so the two will never be equal.
Also note that it is best to append to the list and verify that no divisors where found only after the inner loop has finished.
This modified version works.
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
var initNum;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
}
if (currCompose == ceiledNum+1)
{
arr[currIndex] = initNum;
++currIndex;
}
}
return arr;
}
var primes = findPrimes(6);
document.write(primes);
correct Line 14 of your code as follows and it works like charm.
for (currCompose = 2; currCompose <= initNum; ++currCompose)
function FindPrime(numbers){
if(numbers.constructor === Array){
output = [];
for (var i = numbers.length - 1; i >= 0; i--) {
if(isPrime(numbers[i]) == true){
output.push(numbers[i]);
};
};
return output;
}
}
function isPrime(numb){
if (numb % 2 == 0) return false;
for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
if (numb % i == 0) {
return false;
}
}
return true;
}
numbers = [1,2,3,4,5];
test = FindPrime(numbers);
console.log('testing', test);
In my sortable table, I have nulls being sorted to the bottom, numbers parsed into integers, and strings lowercased, all through a series of if/else statements.
I am trying to get the strings with special characters sorted at the top.
If I give it a value of a number, it will go into the number loop and parsed.
If I give it a null value, it will go into the null loop.
How would I go about this?
$('#column1').click(function(e) {
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function()
{
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function()
{
return this.replace(/\s+$/,"");
}
var specChar = /[a-zA-Z1-9]/;
var $sort = this;
var $table = $('#sort-table');
var $rows = $('tbody > tr',$table);
if($($sort).attr('class')== 'asc'){
$rows.sort(function(a, b){
var keyA = (($('td:eq(0)',a).text()).toLowerCase()).trim();
var keyB = (($('td:eq(0)',b).text()).toLowerCase()).trim();
if(!isNaN(keyA) || !isNaN(keyB) )
{
if(keyA.length <1 || keyB.length < 1)
{
if(keyA.length <1 && keyB.length >1)
{
keyA = "zzzzzzzzzzzzzzz";
}
else if(keyB.length <1 && keyA.length >1)
{
keyB = "zzzzzzzzzzzzzzz";
}
else
{
keyA="zzzzzzzzzzzzzzz";
keyB="zzzzzzzzzzzzzzz";
}
}
else
{
if(!isNaN(keyA) && isNaN(keyB))
{
keyA= parseInt(($('td:eq(0)',a).text()));
}
else if(!isNaN(keyB)&& isNaN(keyA))
{
keyB= parseInt(($('td:eq(0)',b).text()));
}
else
{
keyA= parseInt(($('td:eq(0)',a).text()));
keyB= parseInt(($('td:eq(0)',b).text()));
}
}
}
else if ( specChar.test[keyA] == true || specChar.test[keyB] == true)
{
console.log("this worked " + keyA + " " + keyB)
if(specChar.test[keyA] == true && specChar.test[keyB] == false)
{
keyA = null;
}
else if(specChar.test[keyB] == false && specChar.test[keyA] == false)
{
keyB = null;
}
else
{
keyA = null;
keyB = null;
}
}
else
{
}
$($sort).attr('class', 'desc');
return (keyA < keyB) ? 1 : -1;
});
$.each($rows, function(index, row){
$table.append(row);
$("tr:even").css("background-color", "#FF004D");
$("tr:odd").css("background-color", "#FFDD00");
});
}
else {
$rows.sort(function(a, b){
var keyA = (($('td:eq(0)',a).text()).toLowerCase()).trim();
var keyB = (($('td:eq(0)',b).text()).toLowerCase()).trim();
if(!isNaN(keyA) || !isNaN(keyB) )
{
if(keyA.length <1 || keyB.length < 1)
{
if(keyA.length <1 && keyB.length >1)
{
keyA= "zzzzzzzzzzzzzzz"
}
else if(keyB.length <1 && keyA.length >1)
{
keyB= "zzzzzzzzzzzzzzz"
}
else
{
keyA= "zzzzzzzzzzzzzzz"
keyB= "zzzzzzzzzzzzzzz"
}
}
else
{
if(!isNaN(keyA) && isNaN(keyB))
{
keyA= parseInt(($('td:eq(0)',a).text()));
}
else if(!isNaN(keyB)&& isNaN(keyA))
{
keyB= parseInt(($('td:eq(0)',b).text()));
}
else
{
keyA= parseInt(($('td:eq(0)',a).text()));
keyB= parseInt(($('td:eq(0)',b).text()));
}
}
}
else if ( specChar.test(keyA) == false || specChar.test(keyB) == false)
{
console.log("this worked " + keyA + " " + keyB)
if(specChar.test(keyA) == false)
{
keyA = " ";
}
else if(specChar.test(keyB) == false)
{
keyB = " ";
}
else
{
keyA = " ";
keyB = " ";
}
}
else{}
$($sort).attr('class', 'asc');
return (keyA > keyB) ? 1 : -1;
});
$.each($rows, function(index, row){
$table.append(row);
$("tr:even").css("background-color", "#FF004D");
$("tr:odd").css("background-color", "#FFDD00");
});
}
e.preventDefault();
});
I've create a Fiddle that sorts an array.
JavaScript
var array = ["a", "!", "2", "", "b", "1", null, "C"],
sortedArray;
sortedArray = array.sort(function(a, b) {
if (a === "") return 1;
if (b === "") return -1;
if (a === null) return 1;
if (typeof a === 'string') {
a = a.toLowerCase();
}
if (typeof b == 'string') {
b = b.toLowerCase();
}
return b < a ? 1 : -1;
});
console.log(sortedArray); // => ["!", "1", "2", "a", "b", "C", null, ""]
You can probably tweak it further to your own taste.