Search code examples
reactjsparseint

cannot parseInt in React project keep getting NaN


enter image description here 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]`


Solution

  • 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