1

I want to find a particular element from an array and remove all next elements from that particular array.

below is my code:

var data1 = [a,b,c,d,e,f,g,h];

var data2 = c; // this is element, that i want to find from data1 and 
remove all next element i.e. d, e, f, g, h .

And I want output like: var res = [a,b,c];

Thanks,

rohit13807
  • 605
  • 8
  • 19

1 Answers1

1

Use splice(). You need to get the index of data2 value in data1 and then use that index to remove all the elements after that in data1.

var data1 = ['a','b','c','d','e','f','g','h'];
var data2 = 'c';
data1.splice(data1.indexOf(data2)+1, data1.length);
console.log(data1);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62