Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

61
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?

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs