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