What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript.

The array I am working with is as follows:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];

My goal is to delete every second and third element to achieve the following result:

["Banana", "Orange", "Apple"]

I attempted using a for-loop along with splice like this:

for (var i = 0; fruits.length; i = i+3) {
    fruits.splice(i+1,0);
    fruits.splice(i+2,0);
};

However, this approach gives me an empty array because the elements are being removed while the loop is still running.

Can anyone guide me on how to correctly accomplish this task?

Answer №1

You have the option to take a different perspective and push() the unwanted value into a separate Array for deletion:

var initialFruits = []

for (var i = 0; i < fruits.length; i = i+3) {
    firstFruits.push(fruits[i]);
};

While this method may not be as concise as using splice(), it does enhance readability.

Answer №2

To extract specific elements from an array, you can utilize the filter method:

var extractedElements = [
   "Dog", 
   "brown", 
   "3", 
   "Cat", 
   "black", 
   "7", 
   "Bird", 
   "blue", 
   "5"
].filter(function(_, index) {
    return index % 3 === 0;
})

This will result in:

["Dog", "Cat", "Bird"]

Answer №3

This method has been successful for me.

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"];

for(var i = 0; i < fruits.length; i++) {
    fruits.splice(i+1,2);
}

//fruits = Banana,Orange,Apple,Pear

A more enhanced demonstration can be found here: http://jsfiddle.net/RaRR7/

Answer №4

Consider iterating over the array in a reverse manner

Answer №5

One potential solution could be to create a new array by duplicating the first, fourth, and seventh elements. While this approach may not be optimal in terms of memory efficiency, it should still meet your needs.

Answer №6

To efficiently process the array, it is recommended to iterate through it in reverse order. If the condition i % 2 == 0 || i%3 == 0 is met for an element, you can remove that specific element using the splice method.

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

The scroll function is executed only one time

I'm currently working on implementing a sticky sidebar snippet using jQuery. However, I am facing an issue where the function within .scroll() is only executing once instead of on every scroll event. Can anyone help me identify what I might be doing i ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

What regular expression should be used to meet the following requirement in JavaScript?

Criteria: Find words that begin with 'a' and end with 'b', with a digit in the middle, but are not on lines starting with '#' Given string: a1b a2b a3b #a4b a5b a6b a7b a8b a9b Expected output: a1b a2b a3b a7b a8b ...

Determine whether the input fields contain specific text

I'm currently working on a script that checks if the user input in an email field contains specific text. It's almost there, but it only detects exact matches instead of partial matches. If the user enters anything before the text I'm trying ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...

Troubleshooting Block-scoped errors on Heroku using Node.js and Express

Currently, I am working with node.js and express on the Heroku platform. While working on the route file, I encountered an issue when using the let keyword. The error message displayed was: SyntaxError: Block-scoped declarations (let, const, function, cla ...

I am looking to retrieve the body's background color using Regular Expressions

Trying to extract the background color from a CSS string: "body{ background-color: #dfdfdf; } " The color could also be in rgba(120,120,120) format. I am looking for a way to extract that color using regular expressions. I have tried using this patt ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

Transitioning my website to incorporate Angular JS

Recently, I have been exploring AngularJS and I am quite impressed with its features. I am currently developing a website using traditional methods (php, html, css, mysql, some jQuery) and I am considering transitioning to Angular. The reason for this chan ...

Angular page fails to refresh upon addition or deletion of data

There's a recurring issue with my angular application where the page fails to refresh after data manipulation such as addition, editing, or removal. For example, when I add a new item to a list of subjects, it doesn't show up unless I navigate aw ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

Refresh the angular form after submitting data

I am currently working on an angular form to input data into a database. My framework of choice is angular-fullstack by yeoman. After successfully submitting the data, I encounter an issue where clearing the form values doesn't allow me to add new en ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...

A guide on how to retrieve POST form fields in Express

My form design is quite simple: <form id="loginformA" action="userlogin" method="post"> <div> <label for="email">Email: </label> <input type="text" id="email" name="email"></input> </div> & ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Exploring the Exciting World of Jquery Cycle and Dynamic Ajax Capt

Utilizing Jquery Cycle for image fading loaded by Ajax, along with displaying corresponding captions using the onBefore option in the plugin. The image transition is functioning perfectly, however, there seems to be a slight issue with the caption display. ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...