Eliminating every third and fourth element out of a set of five elements

I need to manipulate an array where elements are in increments of 5, and I specifically need to drop the 3rd and 4th elements.

Currently, I have a solution using two separate for-loops, but I believe there might be a more efficient or concise approach. Any suggestions?

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

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

  // dropping every 3rd element out of 4
  for (let i = 2; i <= arr.length; i += 3) {
    arr.splice(i, 1);
  }

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

Answer №1

Instead of removing elements one by one in a loop, you can achieve the same result by removing 2 elements at once in a single loop.

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

Answer №2

If I were to opt for creating a fresh array, here's how I would proceed:

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

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

for (let i = 0; i < data.length; i++) {
  const modifiedIndex = i % 5;
  if (!restrictedIndices.includes(modifiedIndex)) {
    result.push(data[i]);
  }
}

console.log(result);

Alternatively, for a more sophisticated approach:

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

var filterFunction = (filteredData, currentElement, index) => {
  const modifiedIndex = index % 5;
  const restrictedIndices = [2, 3];
  
  if (!restrictedIndices.includes(modifiedIndex))
  {
    filteredData.push(currentElement);
  }

  return filteredData;
}

var outcome = data.reduce(filterFunction, []);
console.log(outcome);

This enhances the solution's versatility by allowing easy modification of filtering parameters in the future.

Answer №3

An effective way to eliminate the 3rd and 4th indexes from an array is by utilizing the Array filter prototype.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery Ajax hover event triggering even after mouse has left the element

Currently in the process of developing a tooltip with jQuery that fetches content via Ajax request and stores it in a variable to prevent continuous firing of Ajax calls upon every mouseover. The functionality is working flawlessly, barring one issue - whe ...

jQuery returns varying values for checked status when using click() method versus manual click

I'm facing an issue with a checkbox generating dynamic content. Whenever I try to pre-create the dynamic content on page load by using click(), the "checked" attribute is not set until after the click function finishes. Strangely, when I manually cli ...

Combining Jquery with Objects and Strings

Having a bit of trouble with a small issue that I can't seem to figure out. Let me explain... So, I'm creating an input like this... var input = $('<input/>'); When I append it like this, everything works fine: $(this).append( ...

Generate a new entry and its linked data simultaneously

The Issue: Picture this scenario: I have two connected models, Library which has multiple Books: var Library = sequelize.define('Library', { title: Sequelize.STRING, description: Sequelize.TEXT, address: Sequelize.STRING }); var Boo ...

How to use a variable as a jQuery selector

My webpage includes a dropdown/select menu that reveals different divs based on the user's selection. Each div contains another dropdown/select menu that I want to trigger an action when changed. The issue is that the ID of these divs is generated dy ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

Updating elements in an array based on a specified threshold value, all done without the use of conditional if statements in Javascript

I am exploring ways to efficiently solve this particular problem. Within my dataset is an extensive array of integers: [170,158,147,139,134,132,133,136,141,.....] I have predetermined threshold values of 132 and 137. My goal is to adjust any numbers in ...

What is the best way to update an existing cookie value using angularjs?

Currently, I am working with AngularJS. When a button is clicked, I am setting a cookie and it works perfectly fine. However, when the page is refreshed and another button click occurs, a new value is stored in the array while the old cookie value becomes ...

Require assistance with debugging an issue in an online game played through a web browser

Experience a simple browser memory game where you must flip all matching cards to emerge victorious. The glitch : In the game, if you click quickly enough, you can uncover more than two cards at a time. I've spent ample time attempting to rectify t ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

GraphQL failing to communicate with WP API

Any help is appreciated! I am currently retrieving data from a WP Rest API. When I run the WordPress site locally on my machine using http://localhost:8000 and access the graphql playground at http://localhost:3000/api/graphql, everything works fine as ex ...

Generating Unique Random Numbers with JavaScript

Is there a way to generate 5 unique random lottery numbers using JavaScript? I've been working on the code below, but can't seem to figure out how to ensure there are no duplicate numbers in the final selection. I tried adding conditionals and lo ...

Crafting an interactive SVG element that maintains its clickability without interfering with mouseLeave events

Trying to Achieve: Changing color and displaying SVG when hovering over a row Clicking the SVG triggers a function, including external functions (not limited to ones defined inside script tags) Returning the row to its original form when mouse leaves Cha ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

"Exploring the capabilities of React 18 with arrays of

I have a main component called Root, which contains several sub-components known as Panel components. export interface RootProps{ children: React.ReactNode, className?: string, scheme?: 'light' | 'dark', activePanel: str ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

Remove any div elements that do not contain any content

I have a method on my front end that receives HTML as a string from the backend Here is the code snippet: private async tryGetOooMessage(employeeId: string): Promise<string> { try { return await firstValueFrom(this.messages.getOutOfOfficeI ...

Error: Astra connection details for Datastax could not be located

Currently, I am attempting to establish a connection to DataStax Astra-db using the cassandra-client node module. Below is an example of my code: const client = new cassandra.Client({ cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NA ...

Node is unable to execute a CLI tool that is packaged within an NPM package

I am working on creating an NPM package that includes a CLI utility. In the package.json file, I have specified the following line: "bin": "index.js" However, when I install the package on Windows, a batch file named mypackage.cmd is ...