Remove items from an array using other items from another array as the index

Let's consider the following scenario:

let arr1 = [0,2] // This array is always sorted

Just to clarify, these elements in the "arr1" array represent indexes that need to be removed from another array.

We also have another array:

let arrOvj = [1,4,6,7,21,17,12]

The goal here is to remove elements from "arrObj" based on the indexes present in "arr1".

After the deletion process, we expect the output to be:

[4,7,21,17,12].

Now, the attempted solution was using a loop to splice out elements like this:

for(let i=0;i<arr1.length;i++){
   arrObj.splice(arr1[i],1)
}

However, this method provided incorrect results. For instance, if "arr1"=[0], it deleted the first two elements instead of just removing the element at index 0 of "arrObj".

Do you know of an alternate approach I can take to ensure removal only occurs at the specified index values?

Feel free to request more information if needed.

Answer №1

If you want to efficiently delete elements from an array without shifting positions, consider looping backwards over the indices that need to be deleted.

let arr1 = [0,2] 
let arrOvj = [1,4,6,7,21,17,12]
for(let i = arr1.length - 1; i >= 0; i--) arrOvj.splice(arr1[i], 1);
console.log(arrOvj);

Answer №2

Another approach involves utilizing the filter method on the array to eliminate specific indexes like this:

let myArray = [1,4,6,7,21,17,12]
let positions = [0,2]

let filteredArray = myArray.filter((elem, i) => !positions.includes(i));

console.log(filteredArray);

Answer №3

If you're looking to manipulate arrays in JavaScript, consider using splice along with reduceRight.

let array1 = [0, 2];
let objArray = [1, 4, 6, 7, 21, 17, 12];

objArray = array1.reduceRight((accumulator, currentValue) => (accumulator.splice(currentValue, 1), accumulator), objArray);

console.log(objArray);

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

Module 'xhr2' not located

Snippet of code : let XMLHttpRequest = require('xhr2'); let xhr = new XMLHttpRequest(); xhr.open('GET', 'data.json', true); xhr.send(); Issue : internal/modules/cjs/loader.js:969 throw err; ^ Error: Module 'xhr2' n ...

Is it possible to change the background color of a MUI theme in ReactJS by using Css

Currently, I am utilizing Material UI to create a theme that is functioning correctly. However, upon adding <CssBaseline/> to the App.js file, it unexpectedly changes the background color to white instead of the intended #1f262a specified in the inde ...

Developing a Library for Managing APIs in TypeScript

I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that cal ...

Efficiently condense a sequence of ones and zeros into a more compact format, then effortlessly revert it back to the original sequence without any changes. Each time

I've been exploring different approaches in NodeJS and plain JavaScript to improve this task. Currently, I have developed some functions that count the repetition of characters, but I'm curious if there are more efficient methods or potential en ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

What's the significance of including both the starting and ending brackets when transforming an array into JSON using JavaScript?

After converting an array to JSON, I noticed that backslashes are added at the start and end. Why is this happening? // Sample code var myJSON = ""; var FinalResult = JSON.stringify(result); myJSON = JSON.stringify({"result": FinalResult}); document.wri ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

Utilizing JQuery to select list items for pagination purposes

I am currently working on a pagination script and everything seems to be functioning well, except for one minor issue. I am struggling with triggering an action when the page number (li) is clicked. The pagination data is being retrieved via ajax and disp ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

Using jQuery to access OSM data through Overpass API: A step-by-step guide

My current approach to fetch map data from OSM involves the following code: $.ajax({ url: 'https://www.overpass-api.de/api/interpreter?' + '[out:json][timeout:60];' + 'area["boundary"~"administrative" ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

Set the value of a variable to the result of a JavaScript function

I recently wrote a function that retrieves JSON data from a specified URL. Here's what the function looks like: function getJSON(url) { request.get({ url: url, json: true, headers: { 'User-Agent': 'request&a ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...

Implementing html5mode in Express.js and Angular.js for cleaner URLs

I've been working on resolving the issue of avoiding # in my Angular app with an ExpressJS server-side setup. I found a solution to enable html5mode and it worked well. However, whenever there is another 'get' request to fetch data from a di ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

Looking to incorporate an Ajax feature that allows for updating dropdown menus in each row of the database

Please find below the UI screenshot highlighting the dropdown menu: What I am looking for? I would like the option selected in the dropdown menu to be updated for each specific row in the database using AJAX. Below are the codes I have written. As a beg ...

Is there a way to set up my node package to automatically load sources without having to specifically mention the src directory?

My Node package is structured as follows: ./my-package ./src ./index.js ./a.js ./b.js README.md package.json The package.json file specifies "main": "./src/index.js" and the module loads correctly. However, to import a specific JavaScri ...

Communication between Angular Controller and Nodejs Server for Data Exchange

Expanding on the solution provided in this thread, my goal is to implement a way to retrieve a response from the node server. Angular Controller $scope.loginUser = function() { $scope.statusMsg = 'Sending data to server...'; $http({ ...

When utilizing an object within another object for a select option in Vue.js, the value may not update as expected

I'm currently working with an array of posts that includes a user for each post. I have a select field where I can change the user associated with a post. However, only the user's id updates on the page and not their username. Is there a way to e ...

Steps for verifying the following number and contrasting it with the previous one

I have an array containing numbers with a total size of 14. The array is filled with -1 in blank spaces, while the rest of the numbers are like this: [2,3,4,7,8, -1, -1...]. To ensure that the numbers are exactly one apart, I need to compare them and find ...