-2

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?

dumpAndDie
  • 121
  • 2
  • 11

1 Answers1

1

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)
Spectric
  • 30,714
  • 6
  • 20
  • 43