2

I have an array of orders and when i recieve a message from my websocket with a new placement order or a modified order i want to check against my orders array, if there is an exisitng order with the websocket message replace the object in the array with the websocket message, else push it to the array.

example:

const orderArr = [
{
id: 1,
item: 'apple',
price: 20
},
{
id: 2,
item: 'mango',
price: 10
},
{
id: 3,
item: 'cucumber',
price: 300
}
]

const webSocketOrder = {
id: 1,
item: 'apple',
price: 40
}

// what should happen to the order array
[
{
id: 1,
item: 'apple',
price: 40
},
{
id: 2,
item: 'mango',
price: 10
},
{
id: 3,
item: 'cucumber',
price: 300
}
]

but if the webSocketOrder is a new item with a new id it should be added as a new item in the orderArr

what i have done

const foundOrder = orderArr.find(
          (x) => x.id === webSocketOrder.id
        );
        if (foundOrder) {
          orderArr.map((ord) =>
            ord.id === webSocketOrder.id 
              ? webSocketOrder
              : ord
          );
        } else {
          orderArr.unshift(webSocketOrder);
        }

this doesnt work for some reason, please can someone help?

7
  • There is no typescript anywhere in your code... Commented May 26, 2021 at 12:20
  • my mistake, i removed those bits Commented May 26, 2021 at 12:22
  • Read about array operations in detail. Your find, map and unshift usage is wrong Commented May 26, 2021 at 12:23
  • Why are you calling array like a function: orderArr( (x) => ..) Commented May 26, 2021 at 12:24
  • sorry thats meant to be orderArr.find Commented May 26, 2021 at 12:25

2 Answers 2

3

You can use find()/findIndex() to loop over the array just once.

 const index = orderArr.findIndex((obj) => obj.id === webSocketOrder.id);

    if (index === -1) {
        orderArr.push(webSocketOrder);
    } else {
        orderArr[index] = webSocketOrder;
    }

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

1 Comment

Great stuff. Saved my day!
0

If you're replacing the order in place (not treating the array as immutable) you can use splice

const index = orderArr.findIndex((obj) => obj.id === webSocketOrder.id);

orderArr.splice(index > -1 ? index : orderArr.length, index > -1 ? 1 : 0, webSocketOrder);

Comments

Your Answer

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