1

I am new to React and I try to get a summation using for loop in react. To do that I use this code.

function CompanyForms() {

    const { postId, companyId } = useParams();

    const [offers, setOffers] = useState([]);

    useEffect(()=>{
        getAllOffers();
    }, []);

    const getAllOffers = async () => {
        await axios.get(`/viewPendingCompanyOffers`)
            .then ((response)=>{
                const allNotes=response.data.existingOffers;
                setOffers(allNotes);
            })
            .catch(error=>console.error(`Error: ${error}`));
    }
    console.log(offers);

    const wasteItem = offers?.filter(wasteItem => wasteItem.status==='accepted' && wasteItem.companyId===companyId);
    console.log(wasteItem);

    const wasteItemLength = wasteItem.length;
    console.log(wasteItemLength);

    let quantity=0;

    for (let i = 0; i < wasteItemLength; i++) {
       quantity += wasteItem.map(wItem=>wItem.quantity)
    }

    console.log(quantity);

}

First I call the API and get a length 9 array of objects. Then I use the filter function to filter the data that are in length 9 array of objects. As the result of this filter function, I get length two array of objects. This image shows that result.

Results of the filter function

Then I assign the length of the array of objects that get from the filter function to a variable const wasteItemLength = wasteItem.length. Then I use a for loop with operators to get the summation of quantity in two array of objects called as wasteItem.

The quantity field has a value of 20 in both wasteItem array of objects. I try to add these two values using the for a loop. Then when using this console.log(quantity), I should get 40 as the answer. But the problem is I get this

Result

as the result instead of value 40. What is the reason for this problem? How do I solve this problem?

Thank you.

1 Answer 1

1

Array.map returns an array. Its intended usage is returning a new array whose values have been transformed by some function that you pass as the first argument. In your case, you're trying to sum a bunch of arrays when you do quantity += wasteItem.map... inside your loop body. I'm not sure exactly what your goal was in doing that but it seems like a mistake to me.

You have three better options:

  1. Do quantity += wasteItem[i].quantity inside your for loop

  2. Use a for..of loop which is simpler to use and read:

    for(const item of wasteItem) {
      quantity += item.quantity;
    }
    
  3. Use Array.reduce:

    const quantity = wasteItem.reduce((x, sum) => sum + x, 0);
    

By the way, if you name your variable wasteItems, the plural makes it more obvious that it's an array instead of a single item. Variable names are very important to make your code more readable for your future self and others!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.