简体   繁体   中英

Delete every 5th element in an array, but starting at 2nd element

My array is a sequence of 3 groups containing 5 elements.

var tempArray1 = ['prodn', 'PP1', 'UK1', 'Exp', 'India2', 'prodn', 'PP2', 'france1', 'Imp', 'Czech2', 'prodn', 'PP3', 'Germ1', 'Exp', 'Rom2']

I need to delete the 2nd element in my my array, and then delete every 5th element. This will remove all elements starting with "PP". Note that I want to delete with reference to position in array, not by character type. The following is my code to remove every 5th element.

var indexToRemove = 5;  // start position
var numberToRemove = 1; // elements to remove

tempArray1.splice(indexToRemove, numberToRemove);

But how can I start this from the 2nd element? Thank you.

When you use splice you mutate the array (in-place), so you need to take steps of 4 instead of 5 as you already removed one value. Start a for loop at index 1:

 const tempArray1 = ['prodn', 'PP1', 'UK1', 'Exp', 'India2', 'prodn', 'PP2', 'france1', 'Imp', 'Czech2', 'prodn', 'PP3', 'Germ1', 'Exp', 'Rom2']; for (let i = 1; i < tempArray1.length; i += 4) { tempArray1.splice(i, 1); } console.log(tempArray1); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

  var tempArray1 = ['prodn', 'PP1', 'UK1', 'Exp', 'India2', 'prodn', 'PP2', 'france1', 'Imp', 'Czech2', 'prodn', 'PP3', 'Germ1', 'Exp', 'Rom2'] for(i=2-1; i< tempArray1.lenght; i+=5-1){ // start with 2nd element (-1 because arrays start at 0) // and than jump to 5th element (-1 because the one has just been removed) // remove 1 element at i-th place tempArray1.splice(i,1); } 

 const tempArray1 = ['prodn', 'PP1', 'UK1', 'Exp', 'India2', 'prodn', 'PP2', 'france1', 'Imp', 'Czech2', 'prodn', 'PP3', 'Germ1', 'Exp', 'Rom2']; const newArray = tempArray1.filter(function(element, i){ return (i % 5) != 1; }); console.log(newArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM