While adding two numbers getting NAN as output in the react? - reactjs

When I am trying to add two numbers, I am able to get NaN. If anyone has any advice, any help would be greatly appreciated.
This is my Code:-
var sum = parseInt(label.labellength, 10) + parseInt(label.labely, 10);
console.log("Sum of FrontRight is " + sum );
Output is:-NaN
I tried as following :
Using Number
var sum=Number(label.labellength) + Number(label.labely);
Output is:-NaN

The same issue came to me , try to use || operator and return it, it did the same and it worked for me...
const [contextOverHr,setContextOverHr=useState("")
return (
{Object.values(workHour).reduce((pre,total) => {
let totalNum = pre + total.OverHour
setContextOverHr (totalNum)
return totalNum || 0
},0)
}
)

Related

manipulate the decimal without the main number

I am trying to figure out how to fix this problem.
I am greeting my time in this format (15min is 25% of an hour) such as
8.75 mean 8:45
7.50 mean 7:30
I wanted to come out with a simple function to fix that issue But I wasn't successful, any thought?
This function can do it
function calc(number){
const decimal = number.toString().substring(3, 4)
parseInt(decimal)
const result = decimal*60/100
return number.toString()[0] + ':' + result + '0'
}
console.log(calc(8.75))

Calculate sum of props from TextInput

I want to calculate the sum of the props I'm passing to my child component but it seems to only work when I add them in the correct order. Ex. I enter math as 100, science as 100, and so on down the line, it will add correctly. But if I enter math as 100 then art as 100, totalscore will show as 100100 and not 200.
For example:
var totalScore =
this.props.math +
this.props.science +
this.props.history +
this.props.gym +
this.props.lunch +
this.props.art
if (e == 1 || e == 2 || e == 3) {
if (isNaN(totalScore)) {
return totalScore = 'fail';
} else {
return totalScore
}
}
How can I add a value these props in any order with the correct sum?
The problem is not with the order and the order is NOT important. The problem is string concatenation. You are passing string instead of numbers
Explicity typecasting them like below should fix the issue
var totalScore =
Number(this.props.math) +
Number(this.props.science) +
Number(this.props.history) +
Number(this.props.gym) +
Number(this.props.lunch) +
Number(this.props.art)
if (e == 1 || e == 2 || e == 3) {
if (isNaN(totalScore)) {
return totalScore = 'fail';
} else {
return totalScore
}
}
For reference, to pass the props as numbers, do this
<Component someProp={100} >
if you say someProp="100" it will be a string
it seems like the props is a string because the number you enter are concatenated. You can use the parseInt or parseFloat functions, or simply use the unary + operator:
example
var totalScore =
parseInt(this.props.math) +
parseInt(this.props.science)
Or
+this.props.science +
+this.props.math
Or
parseFloat(this.props.math) +
parseFloat (this.props.science)
in short You need to convert the string to number

Booleans, arrays, and not typing 256 possible scenarios

I'm trying to make a program based around 8 boolean statements.
I build the array = [0,0,0,0,0,0,0,0];.
For each possible combination I need to make the program output a different text.
To make things simpler, I can remove any possibilities that contain less than 3 true statements.
For example: if (array === [1,1,1,0,0,0,0,0]){console.log('Targets: 4, 5, 6, 7')};
Is it possible to have it set so that if the value is false it's added to then end of "Targets: "? I'm very new to coding as a hobby and have only made 1 extensive program. I feel like {console.log("Targets: " + if(array[0]===0){console.log(" 1,")} + if(array[2]===0)...}would portay what I'm looking for but it's terrible as a code.
I'm sure that someone has had this issue before but I don't think I'm experienced enough to be searching with the correct keywords.
PS: I'd greatly appreciate it if we can stick to the very basics as I haven't had any luck with installing new elements other than discord.js.
This does what you need:
const values = [1,1,1,0,0,0,0,0];
const positions = values.map((v, i) => !v ? i : null).filter(v => v != null);
console.log('Target: ' + positions.join(', '));
In essence:
Map each value to its respective index if the value is falsy (0 is considered falsy), otherwise map it to null.
Filter out all null values.
Join all remaining indexes to a string.
To address your additional requirements:
const locations = ['Trees', 'Rocks', 'L1', 'R1', 'L2', 'R2', 'L3', 'R3'];
const values = [1,1,1,0,0,0,0,0];
const result = values.map((v, i) => !v ? locations[i] : null).filter(v => v != null);
console.log('Target: ' + result.join(', '));

Merge random elements of array/split into chunks

How can I split array into chunks with some special algorithm? E.g. I need to shorten array to the size of 10 elements. If I have array of 11 elements, I want two next standing elements get merged. If I have array of 13 elements, I want three elements merged. And so on. Is there any solution?
Sample #1
var test = ['1','2','3','4','5','6','7','8','9','10','11'];
Need result = [['1'],['2'],['3'],['4'],['5|6'],['7'],['8'],['9'],['10'],['11']]
Sample #2
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13'];
Need result = [['1|2'],['3'],['4'],['5'],['6'],['7|8'],['9'],['10'],['11'],['12|13']]
Thank you in advance.
The following code most probably does what you want.
function condense(a){
var source = a.slice(),
len = a.length,
excessCount = (len - 10) % 10,
step = excessCount - 1 ? Math.floor(10/(excessCount-1)) : 0,
groupSize = Math.floor(len / 10),
template = Array(10).fill()
.map((_,i) => step ? i%step === 0 ? groupSize + 1
: i === 9 ? groupSize + 1
: groupSize
: i === 4 ? groupSize + 1
: groupSize);
return template.map(e => source.splice(0,e)
.reduce((p,c) => p + "|" + c));
}
var test1 = ['1','2','3','4','5','6','7','8','9','10','11'],
test2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21'];
console.log(condense(test1));
console.log(condense(test2));
A - Find the difference and create thus many random numbers for merge and put in array
B - loop through initial numbers array.
B1 - if iterator number is in the merge number array (with indexOf), you merge it with the next one and increase iterator (to skip next one as it is merged and already in results array)
B1 example:
int mergers[] = [2, 7, 10]
//in loop when i=2
if (mergers.indexOf(i)>-1) { //true
String newVal = array[i]+"|"+array[i+1]; //will merge 2 and 3 to "2|3"
i++; //adds 1, so i=3. next loop is with i=4
}
C - put new value in results array
You can try this code
jQuery(document).ready(function(){
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var arrays = [];
var checkLength = test.length;
var getFirstSet = test.slice(0,10);
var getOthers = test.slice(10,checkLength);
$.each( getFirstSet, function( key,value ) {
if(key in getOthers){
values = value +'|'+ getOthers[key];
arrays.push(values);
}else{
arrays.push(value);
}
});
console.log(arrays);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Arranging the fields of a structure into order

I am trying find away of ordering a polynomial in the form a structure so that the exponent fields are in ascending order. I don't want to use a built in sort function to do this.
for example the polynomial:
p = struct('exponent',{2,3,2,9},'coeff',{1,2,91,40})
represents the polynomial:
p = 1(x^2) + 2(x^3) + 91(x^2)+ 40(x^9)
I want to rearrange it so that it becomes (the exponents are now in ascending order)
p = 1(x^2) + 91(x^2) + 2(x^3) + 40(x^9)
my code to do this is:
function [ output ] = myMergepoly2( p )
h=1;
output(1,length(p))=struct('exponent',{},'coeff',{});
while (h<length(p))
if p(1,h+1).exponent<p(1,h).exponent
output(1,h).exponent = p(1,h+1).exponent;
output(1,h).coeff = p(1,h+1).coeff;
h=h+1;
else
output(1,h).exponent = p(1,h).exponent;
output(1,h).coeff = p(1,h).coeff;
end
end
end
However when I try to run this function MATLAB remote has 'busy' written out with no error message. I am unsure what is causing this and how to fix it, any help would be appreciated.
In the else section of the loop, you don't increment h, so it goes like this:
h=1 --> if p(1,h+1).exponent<p(1,h).exponent is false --> skip to else loop and set output(1,1).exponent --> h=1 (while loop keeps going).
Using MATLAB inbuilt sort I'd just do something along the lines of:
exponent = [p.exponent];
coeff = [p.coeff];
[exponent idx] = sort(exponent);
output.exponent = exponent;
output.coeff = coeff(idx);
Replace this line :
output(1,length(p))=struct('exponent',{},'coeff',{});
With this line :
output = struct('exponent',cell(1,length(p)),'coeff',cell(1,length(p)));
Also put this instead:
while (h<length(p))
if p(1,h+1).exponent<p(1,h).exponent
output(1,h).exponent = p(1,h+1).exponent;
output(1,h).coeff = p(1,h+1).coeff;
else
output(1,h).exponent = p(1,h).exponent;
output(1,h).coeff = p(1,h).coeff;
end
h=h+1;
end
However I'm still not getting the right output, I'm working on it.

Resources