Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
How to change an array element based on another array element

Whats the goal?
Two arrays: orders and NewOrders

Check if there is an order with the same order_id on both arrays, than compare the order status, if the order from the NewOrders array has a different status then set orders[i].status = NewOrders[i].status

My current code:

const {orders} = this.state;

const page = this.state.page;
const newOrders= await api.get('/orders?page='+page);

for (let i = 0; i < newOrders.length; i++) {
    orders[newOrders[i].order_id].status = newOrders[i].status;             
}

It doesn't properly work
How can I make this work using ES6?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you are working in React you must not mutate the state manually. Map orders into a new array, based on the required transformations, then use setState() to update the state.

const _orders = orders.map(o => {
    const found = newOrders.find(no => o.order_id === no.order_id)
    return found
        ? { ...o, status: found.status }
        : o
})

this.setState({orders: _orders})

Example

const orders = [
    { order_id: "1", status: "OK" },
    { order_id: "2", status: "NOK" },
]
const newOrders = [
    { order_id: "2", status: "OK" },
    { order_id: "3", status: "OK" },
]

Output

[
    { order_id: "1", status: "OK" },
    { order_id: "2", status: "OK" },
]
about 4 years ago · Juan Pablo Isaza Report

0

You can use Array#find.

for (const order of orders) {
    const newOrder = newOrders.find(x => x.order_id === order.order_id);
    if(newOrder) order.status = newOrder.status;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!