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

143
Views
Delete a part of array elements in js

I have an Array and want to delete X element and All elements after 'X' element in array and return previous elements

This is my array : ['A' , 'B' , 'C' , 'D' , 'X' , 'Z' , 'A' , 'B' , 'F']

And the new array I want is this : ['A' , 'B' , 'C' , 'D']

How can I did this?

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

0

Use Array.indexOf to get the index of the target and Array.slice to get the items from index 0 to the index of the target:

const arr = ['A' , 'B' , 'C' , 'D' , 'X' , 'Z' , 'A' , 'B' , 'F']
const target = 'X'

const res = arr.slice(0, arr.indexOf(target))

console.log(res)

If you want to modify the original, use Array.splice instead:

const arr = ['A' , 'B' , 'C' , 'D' , 'X' , 'Z' , 'A' , 'B' , 'F']
const target = 'X'

arr.splice(arr.indexOf(target))

console.log(arr)

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!