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

120
Views
adding item in to react state at certain position related to the item at hand?

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 ]

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

0

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);

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!