Home > Enterprise >  Removing every 3rd & 4th out of 5 elements from array
Removing every 3rd & 4th out of 5 elements from array

Time:06-24

I'm getting an array handed to me that has elements in increments of 5; the 3rd and 4th elements of which i need to drop.

I've got a working solution in two separate for-loops, but I feel like there's gotta be a better or more concise way of doing this...any thoughts?

const arr = ["good","good","bad","bad","good","good","good","bad","bad","good",];

// remove every 3rd of 5 elements
  for (let i = 2; i <= arr.length; i  = 4) {
    arr.splice(i, 1);
  }

  // remove every 3rd of 4 elements
  for (let i = 2; i <= arr.length; i  = 3) {
    arr.splice(i, 1);
  }

console.log(arr)
// expected output ["good","good","good","good","good","good"]

CodePudding user response:

You could just do it in a single loop by removing 2 elements, instead of 1.

const arr = Array(50).fill(["good", "good", "bad", "bad", "good"]).flat()

// remove every 3rd of 5 elements
for (let i = 2; i <= arr.length; i  = 3) {
  arr.splice(i, 2);
}

console.log(arr);

CodePudding user response:

If creating a new array is acceptable, I would go the following way:

const array = ["good", "good", "bad", "bad", "good", "good", "good", "bad", "bad", "good", ];

var result = [];
const disallowedIndices = [2, 3];

for (let i = 0; i < array.length; i  ) {
  const normalizedIndex = i % 5;
  if (!disallowedIndices.includes(normalizedIndex)) {
    result.push(array[i]);
  }
}

console.log(result);

or if you want to make it a little bit more fancy:

const array = ["good","good","bad","bad","good","good","good","bad","bad","good",];

var reduceFunction = (filteredArray, currentElement, index) => {
  const normalizedIndex = index % 5;
  const disallowedIndices = [2, 3];
  
  if (!disallowedIndices.includes(normalizedIndex))
  {
    filteredArray.push(currentElement);
  }

  return filteredArray;
}

var result = array.reduce(reduceFunction, []);
console.log(result);

It makes the solution more versatile allowing the filtering parameters to be easily modified in the future.

CodePudding user response:

You can use the Array filter prototype to filter out 3 & 4 index

const arr = Array(50).fill(["good", "good", "bad", "bad", "good"]).flat()
const disAllowedIndex=[2,3]
const filteredArray=arr.filter((item,index)=>!disAllowedIndex.some(i=>i==index%5))
  • Related