cannot parseInt in React project keep getting NaN - reactjs

Ok, so I am currently trying to add items from an object together prices to be exact. When I try to actually parse the items with parseInt,I keep getting NaN.
I have tried to replicate it on repl.it and it works fine, also I have tried to use Number instead of parseInt and same results.
class Cart extends Component {
constructor(props) {
super(props);
this.add = this.add.bind(this);
}
componentDidMount() {
this.props.getCart();
}
add(array) {
let num = [];
let parse = [];
console.log(array);
for (let i = 0; i < array.length; i++) {
parse.push(array[i].price);
}
console.log(parse);
for (let i = 0; i < parse.length; i++) {
num.push(parseInt(parse[i]));
}
console.log(num);
let sum = num.reduce((acc, val) => {
return acc + val;
}, 0);
console.log(sum);
}
render() {
const { cart } = this.props.itemReducer;
this.add(cart);
I do have a few console.log's
first one does show my obj's
the second show's that I pulled my numbers in the variable["$379.99", "$1,499.99"]
the third one where I actually do the parseInt function is when i get [NaN, NaN]`

There is a $ sign in your string. Remove the sign and try
let nanNum = parseInt("$1477")
console.log(nanNum) //This will print NaN
let parsedNum = parseInt("$147,7.05".replace(/[^0-9\.]+/g,""))
console.log(parsedNum)

This is because of ["$379.99", "$1,499.99"], here items in array contains $ which is not a number (NaN) causing the error.
Instead of this,
num.push(parseInt(parse[i]));
You can do this,
num.push(Number(parse[i].replace(/[^0-9.]/g, "")));
Demo

Related

Getting the sum for all of the object retrieve from SharePoint API

.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
const AssociateArray = []
AssociateArray.push({dataTotal : Number})
let associateSum: number = 0;
AssociateArray.forEach(a => associateSum += a.value);
console.log(associateSum);
},
This is my code. I have pushed all of the object into an array. but when i try to sum it up. the console log a NaN.
p.s: this is my first time with stackoverflow
There are a number of issues in your code
1. Incorrect type declaration
You have declared dataTotal : Number For types you need to use number not Number hence dataTotal : number
2. You are adding a type to an array!
Consider the code AssociateArray.push({dataTotal : Number}). {dataTotal : Number} is basically a type so you are pushing an empty type to the array...
3. You can use other means to sum e.g using reduce
With these in mind you can change your code to
.subscribe((dataTotal) => {
this.toGetHourData = dataTotal;
let associateSum: number = dataTotal.reduce((prev, next) => prev + next.value , 0);
console.log(associateSum);
}
.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
var clean = []
var totalnum = 0;
var associateArray = dataTotal
associateArray.forEach(element => {
if (element.strTotalAssociates !== NaN) {
clean.push(element)
console.log(element)
totalnum += element.strTotalAssociates;
console.log(totalnum)
}
});
this is the answer that me and my colleague came up with and its work.

Array already filled after initialization when i want to sort an array

I would like to sort my array to do this I declared 2 temporary array but the both array are already filled even just after the initialization.
Seems like i got a memory problem
let tmpCheckDeals : any[] = [];
let tmpUncheckDeals: any[] = [];
console.log('Init :' , tmpCheckDeals, tmpUncheckDeals);
this.checkedDeals.forEach(element => {
tmpCheckDeals.push(element);
});
for (let i = 0; i < this.deals.list.length; i++) {
let isInside : boolean = false;
const element = this.deals.list[i];
for (let a = 0; a < this.checkedDeals.length; a++) {
const element1 = this.checkedDeals[a];
if(element == element1)
isInside = true;
}
if(isInside == false) {
console.log('Passe');
tmpUncheckDeals.push(element);
}
isInside = false;
}
Result of my console:
console
As you can see my arrays are already filled
Do you have an idea why i get this error pls ?
Thanks
Your code is working as expected. The console displays the value of the array after the entire code has been executed. If you hover over the "i" icon near the array, it would say "Value below was evaluated just now".
For confirmation, you can check by commenting out the remaining code, except the console log.

How to convert JSON to URL params string as per my expected value?

I am working on an angular project. For a method getting a response JSON to convert stringify and POST a body to an API is done. Now the problem is for another one function I should send this value as a URL parameter I tried some ways but didn't get expected result. Please find the below codes and help me out. Thanks
Here is my JSON format value
const bodyJSON = [{FullPackageIDs:[11,7],
PartialPkg:[
{PackageID:4,
FormsList:[
{Form_Name:"Form name One"},
{Form_Name:"Form name Two"}]},
{PackageID:6,
FormsList:[
{Form_Name:"Form name Three"},
{Form_Name:"Form name Four"},
{Form_Name:"Form name Five"}
]
}
]
}]
My expected URL string value like below
http://localhost:4200/DownloadPackage?FullPackageIDs[0]=11&FullPackageIDs[1]=7&PartialPkg[0].PackageID=4&PartialPkg[0].FormsList[0].Form_Name=Form name One&PartialPkg[0].FormsList[1].Form_Name=Form name Two&PartialPkg[1].PackageID=6&PartialPkg[0].FormsList[0].Form_Name=Form name Three&PartialPkg[1].FormsList[1].Form_Name=Form name Four&PartialPkg[2].FormsList[2].Form_Name=Form name Five
I tried via forloop but didnt get expected result. Here is the code for what I tried.
for (let i = 0; i < getSelectedId.length; i++) {
fullPackageParams = `${fullPackageParams}FullPackageIDs[${i}]=${getSelectedId[i]}&`;
for (let j = 0; j < getPartialId.length; j++) {
// const getPartialName = this.partialPackage.map(res => res[i].FormsList);
const getPartialName = getPartialId[j].FormsList;
partialPackageIDParams = `${partialPackageIDParams}PartialPkg[${j}].PackageID=${getPartialId[j].PackageID}&`;
for (let index = 0; index < getPartialName.length; index++) {
partialPackageNameParams = `PartialPkg[${index}].FormsList[${index}].Form_Name=${getPartialName[index].Form_Name}&`;
}
}
}
console.log('params for full packages', fullPackageParams + partialPackageIDParams + partialPackageNameParams);
even if it seems kinda strange to me that you need to pass all of those params using query, you can try this
it just uses ES6 map, reduce functions to create your query string
let URLQuery = bodyJSON.map(value => {
const packageIDs = value.FullPackageIDs.map((v, i) => `FullPackageIDs[${i}]=${encodeURIComponent(v)}`);
const partialPkgs = value.PartialPkg.map((v, i) => {
const startKey = `PartialPkg[${i}]`;
return [
`${startKey}.PackageID=${v.PackageID}`
].concat(
v.FormsList.map((v, i) => `${startKey}.FormsList[${i}].Form_Name=${encodeURIComponent(v.Form_Name)}`)
);
}).reduce((arr, v) => {
return arr.concat(v)
}, []);
return packageIDs.concat(partialPkgs);
}).reduce((arr, v) => {
return arr.concat(v);
}, []).join("&");
const fullURL = `https://example.com?${URLQuery}`;

Use passed parameters in for loop - React Native

I have two classes. In the first one I am fetching from an API. Then I am passing the data to the other class using props.navigation. I can display the data but I want to use those data in a For loop as in this code:
renderText = () => {
const obje = this.props.navigation.state.params.item;
Console.log(obje) //this prints correctly
for (let i = 0; i < obje.length; i++) {
console.log(obje) //this doesnt print anything
if (obje[i].name != null) {
console.log(obje}
}
}
EDIT:
When I try to print const obje, it prints. But when I try to print obje inside the for loop it doesnt, so I guess its not even going through the for loop at all.
Try this way:
renderText = () => {
const obje = this.props.navigation.state.params.item;
console.log(obje) //this prints correctly
Object.keys(obje).map((item) => {
if(item == 'name'){
console.log(obje[item])//YOU CAN PRINT NAME'S VALUE LIKE THIS
}
})
}

React - How to separately assign click event to bunch of div's generated in loop

I am trying to create my own Game of Life in React. Currently have created a map with divs that will be separate cells in future when I finish my project. I also wanted to attach click event to each cell, but for some reason when I click single cell, the entire set of cells is affected. Can you please check why this happens? Also, can you please let me know if my approach is correct? Here is my index.js code:
class Board extends React.Component {
constructor(props){
super(props);
this.state = {isToggleOn: true};
this.changeState = this.changeState.bind(this);
}
changeState() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
createMap = (cols, total) => {
let table = []; let nL = ''; let idRow = 0; let idCol = 0;
for (let i = 0; i < total; i++) {
idCol++;
if (i%cols === 0){
nL = 'newLine';
console.log(i%cols);
idRow += 1;
idCol = 0;
}
else {
nL = '';
}
let toggledBackground = (this.state.isToggleOn ? 'test' : '');
table.push(<div id={"row-"+idRow+"-"+idCol} className={nL+" square "+toggledBackground} onClick={this.changeState}></div>);
}
return table;
}
render() {
return(
<div>
{this.createMap(COLS, FIELDS)}
</div>
);
}
}
All of them are highlighted because they all share the same state, the easiest solution would be to make a separate component for the squares and pass down the needed data as props.
This will allow you to have separate state for every single cell.
I assume FIELDS is the total number of cells (e.g for a 10x10 board, that would make FIELDS = 100). If that's the case, then you could bind the current index for each iteration to the said cell you are pushing in.
This way, you'll know which cell was clicked.
onClick={() => this.changeState(i)}
You'll also need to add a parameter to the actual function declaration, and save the state for that particular cell:
changeState(index) {
this.setState(prevState => {
let arr = prevState.cellStates.slice();
arr[index] = !arr[index];
return {cellStates: arr};
});
}
Of course, this requires you to have an array, not a single boolean:
this.state = {cellStates: Array(FIELDS).fill(false)};
and finally for your styles:
let toggledBackground = (this.state.cellStates[i] ? 'test' : '');

Resources