Home > other >  How to array.splice from both ends simultaneously in Javascript?
How to array.splice from both ends simultaneously in Javascript?

Time:12-08

How do you splice from both ends of an array either simultaneously or sequentially such that "leftsplice" number of fields are spliced from left and "rightsplice" number of fields are spliced from original array not the one after doing leftsplicing. Any tips?

  const [skillname,setSkillName] = useState(["Engineering", "Product", "Organization", "Business", "Market", "Customer"]);
    setSkillName(skillname => skillname.splice(0,leftsplice))
    let temp=-5 leftsplice;
    setSkillName(skillname => skillname.splice(temp, rightsplice))

This is doing only leftsplicing. PS: leftsplice, rightsplice are working as desired. I console.logged them

CodePudding user response:

Your code in splicing is okay, but you should only use setSkillName after both leftsplice and rightsplice is done by saving it from a temporary value, I haven't tested this code below but it is answering the question "How to splice both at the same time from a state" :

function whatever() {
  let tempSkillName = [...skillname]
  tempSkillName = tempSkillName.splice(0,leftsplice))
  let temp=-5 leftsplice;
  tempSkillName = tempSkillName.splice(temp, rightsplice))
  setSkillName(tempSkillName)
}
  • Related