aBloomer aBloomer - 1 month ago 5x
Javascript Question

How to remove all element after a specific element of array?

Below is my array....

["AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "DDD"]

What can I do to get a array back like ["AAA", "BBB", "CCC"]

for example, if the first element is "AAA", I want to delete all element after second "AAA"(second "AAA" also remove)



You can do this easily using indexOf and slice methods of array in javascript.

var arr = ["AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "DDD"];
var firstElem = arr[0];
var secondIndex = arr.indexOf(firstElem, 1);

// Output: ["AAA", "BBB", "CCC"]
var newArr = (secondIndex != -1) ? arr.slice(0, secondIndex) : arr;

Working Fiddle: https://jsfiddle.net/4f25wyaj/2/