Eliminate multiple elements from an array based on their index positions, and then save the

What is the most efficient way to remove multiple items by index and save them in arrays actives and availables? I need to move selected elements from a ListBox, represented as selectedValues = [1, 4, 2].

Here's my proposed solution:

var actives = [ "a", "d", "k", "e"]
var availables = [ "m", "o", "v" ]
var selectedValues = [3, 1]
var elementsToMove = []

selectedValues.forEach(i => {
  elementsToMove.push(actives[i])
})

actives = actives.filter(item => !elementsToMove.includes(item))
availables = availables.concat(elementsToMove);

console.log(actives);
console.log(availables);

Expected result:

actives = [ "a", "k" ]
availables = [ "m", "o", "v", "e", "d"] 

Note: The size of the arrays can vary greatly.

Answer №1

Using a .filter with an .includes within can result in a computational complexity of O(n ^ 2), especially for large inputs. To mitigate this, consider transforming the elementsToMove into a Set to reduce the overall complexity to O(n). Additionally, you can streamline the creation of the elementsToMove array by utilizing .map instead of combining forEach and push:

var actives = [ "a", "d", "k", "e"]
var availables = [ "m", "o", "v" ]
var selectedValues = [3, 1];
const elementsToMove = selectedValues.map(i => actives[i]);
const elementsToMoveSet = new Set(elementsToMove);

actives = actives.filter(item => !elementsToMoveSet.has(item))
availables = availables.concat(elementsToMove);

console.log(actives);
console.log(availables);

Answer №2

To efficiently move elements from one array to another, you can use a single loop and push the spliced elements to the target array.

var sourceArray = [ "apple", "banana", "cherry", "date"],
    destinationArray = [ "mango", "orange", "pear" ],
    indexesToMove = [2, 0];

indexesToMove.forEach(index => destinationArray.push(...sourceArray.splice(index, 1)));

console.log(sourceArray);
console.log(destinationArray);

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

Maintaining the Syntax when Copying HTML to a Text Area

In my project, I rely on markdown for text editing. The markdown is converted to HTML and then stored in the database for display in the view. When users want to edit a post, the stored text is retrieved from the database and used as the initial value in ...

new cookies are created without human intervention

Working on a project in Next.js and using the react-cookie npm package for managing sessions. I am creating a cookie with the key name "token" and assigning the token value as its value. However, an issue has arisen related to cookies where multiple cooki ...

Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, wh ...

What is the best way to create a menu that can be hovered over but not clicked on

This HTML code includes a dropdown menu created using Bootstrap. It contains navigation links for Home, Add User, Export, and Logout. <ul class="nav navbar-nav navbar-right"> <li <?php if($tabs=='home' or $tabs=='') ech ...

The CSS link will only appear when hovering over the image

I'm having trouble getting the f1 link to appear on an image only when hovering over the image. I tried some code but it's not working, the link is not appearing. Can someone help me understand what the problem is and provide a solution? <div ...

Angular model does not bind properly to Bootstrap 3 DateTimePicker after 'dp.change' event

I am currently implementing the Bootstrap 3 DateTimePicker plugin by eonasdan. While everything seems to be functioning correctly, I have encountered an issue with binding the selected date within the input field to Angular's ng-model. Whenever I make ...

Start the Vue component only after ensuring that the element has been fully loaded

I have created a small vue.js component in JavaScript. Is there an elegant way to instantiate the vue component only when the element is loaded? The problem I am facing is that I'm receiving warnings in other HTML files where the element does not ex ...

Display a loading component within the navbar in React while waiting for data to be retrieved

I recently updated my navbar component to accept dynamic values for menu titles. One of these dynamic values is the username, which needs to be fetched asynchronously. To handle this, I decided to display a loading animation until the username is fully fet ...

When trying to use preact as an alias for react, the error "Module not found: 'react/jsx-runtime'" is thrown

Avoid using the outdated guide I linked; follow the one provided in the answer instead I am trying to transition from react to preact by following their migration guide. I updated my webpack.config.js to include: alias: { "react": "pr ...

Storing data in MongoDB upon the emission of a Socket.io event

In my project, I am using a MEAN stack and Socket.io to retrieve images from the real-time Instagram API. The current setup is functioning well, but now I want to store image data in a MongoDB database to maintain a record of images based on locations, rat ...

Can you please explain the purpose of the state object in the setSearchParams hook of react-router-dom v6

Can anyone explain the { state: ? } parameter used in the update function of useSearchParams? const [search, setSearch] = useSearchParams(); setSearch( { ...Object.fromEntries(search), transFilters: JSON.stringify(filters), }, { ...

No data being fetched through Ajax

I am facing an issue with retrieving PHP data in the form of an array. I have created an AJAX query to display data in two divs: one is a drop-down and the second is where all data will be shown. However, the problem is that when I attempt to do this, all ...

Is there a way to change the visibility of a form element within a directive with the help of

Consider a scenario where you have a basic form as shown below: <form ng-submit="methods.submit(formData)" ng-controller="diamondController" name="diamond" novalidate> <help-block field="diamond.firstName"></help-block> <input ...

Adding a fresh selection to the Bootstrap menu

I'm working on a straightforward Bootstrap form that includes a select input: <div class="form-group"> <label for="category" class="control-label col-sm-3">Category</label> <div class="input-group col-xs-8"> <sele ...

What could be the reason behind encountering a "Cannot return null for non-nullable field" error while attempting a mutation?

Exploring (Apollo) GraphQL on the server side has presented me with a puzzling issue. I have been attempting to register a user, but I keep encountering the error documented in the linked image below. What could be causing this problem? Let's disregar ...

Converting Javascript tools into Typescript

I'm currently in the process of migrating my Ionic1 project to Ionic2, and it's been quite an interesting journey so far! One challenge that I'm facing is how to transfer a lengthy list of utility functions written in JavaScript, like CmToFe ...

Displaying variables in JavaScript HTML

<script type ="text/javascript"> var current = 0; </script> <h3 style={{marginTop: '10', textAlign: 'center'}}><b>Current Status: <script type="text/javascript">document.write(cur ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

In a Django template, implement a checkbox feature in the list view to select multiple objects. Retrieve all selected checkbox objects for each pagination and display them in

In my HTML template, I have a list view with checkboxes and pagination. My goal is to retrieve all the checked box objects from each page's pagination and send them to the server (specifically the view part of Django). For example, if I check 4 object ...

Unveiling the Power of KnockoutJS: Displaying HTML Content and Populating

I am trying to achieve a unique effect using KnockoutJS. Let's consider a basic model: var Item = function () { var self = this; self.title = ko.observable(""); }; In addition, I have a ViewModel: var ItemList = function () { var self = ...