How to update state array to add a value after related position rather than at the end of the array ? in the example below for example I want rice to go after rice rather than after bananas ? , this current logic is making thing really mixed when I want to render items according to what the user has selected to be the first item.
let stateArr = [{item : cucumber}, {item : rice }, {item: bannan }, {item : rice }]
// current state logic
[...stateArr, newItem ]
If you want to keep things immutable, you can slice your array at the point you want to insert the new item, and spread those two slices around your new value.
let stateArr = [
{ item: "cucumber" },
{ item: "rice" },
{ item: "bannan" },
{ item: "fish" },
];
// First, find the location of the item you want to insert _after_
const riceIndex = stateArr.findIndex(({ item }) => item === "rice");
const newItem = { item: "crab" };
// Next, slice _right after_ that item (+ 1)
const newState = [
...stateArr.slice(0, riceIndex + 1),
newItem,
...stateArr.slice(riceIndex + 1),
];
console.log(newState);