Filtering an array by eliminating items stored in other arrays at corresponding indexes that were also removed

I need to filter out specific items from an array (testCopy) while also removing the corresponding items in other arrays (testCopy2 and testCopy3). For example, I want the filtered result to be testCopy [0, 2], testCopy2 [1,3], and testCopy3 [3,5]. Essentially, I want to remove the same items from the other two arrays that were removed from the index being filtered. I attempted to slice them off by using the filter but it didn't work as expected. Do you have any suggestions on how to achieve this?

let test = [0, 1, 2, 4, 5];
let test2 = [1, 2, 3, 6, 5];
let test3 = [3, 4, 5, 8, 9];

let testCopy = [...test];
let testCopy2 = [...test2];
let testCopy3 = [...test3];

let testClone = testCopy.filter((item, index) => {
  if (item === 0 || item === 2) {
    return true;
  } else {
    testCopy2.splice(index, 1);
    testCopy3.splice(index, 1);
    return false
  }
});

console.log(testClone, testCopy2, testCopy3); // [0, 2],  [1, 3, 6], [3, 5, 8]

Answer №1

If you wish to skip the initialization of testCopy2 and testCopy3, here is an alternative approach:

let test = [0, 1, 2, 4, 5];
let test2 = [1, 2, 3, 6, 5];
let test3 = [3, 4, 5, 8, 9];

let testCopy = [...test];
let testCopy2 = [];
let testCopy3 = [];

let testClone = testCopy.filter((item, index) => {
  if (item === 0 || item === 2) {
    testCopy2.push(test2[index]);
    testCopy3.push(test3[index]);
    return true;
  } else {
    return false;
  }
});

console.log(testClone, testCopy2, testCopy3);

Answer №2

If you want to inject a null using splice and then filter them out, keep in mind that it may involve multiple loops.

const test = [0,1,2,4,5];
const test2 = [1,2,3,6,5];
const test3 = [3,4,5,8,9];

const testCopy = [...test];
const testCopy2 = [...test2];
const testCopy3 = [...test3];

const testClone = testCopy.filter((item,index)=>{
    if(item === 0 || item === 2) { 
        return true;
    } else { 
        testCopy2.splice(index,1,null);
        testCopy3.splice(index,1,null);
        return false
    }
});

testCopy2 = testCopy2.filter((val) => val !== null)
testCopy3 = testCopy3.filter((val) => val !== null)

Answer №3

Generate a list of specific items to retain by using the method Array.map() on the initial array, and deciding whether to return true or false based on set criteria. Proceed to filter all arrays using the corresponding index from the collection of items to keep.

const test = [0,1,2,4,5];
const test2 = [1,2,3,6,5];
const test3 = [3,4,5,8,9];

const keepItems = test.map(item => item === 0 || item === 2)
const testCopy = test.filter((_, i) => keepItems[i]);
const testCopy2 = test2.filter((_, i) => keepItems[i]);
const testCopy3 = test3.filter((_, i) => keepItems[i]);

console.log(testCopy, testCopy2, testCopy3); // [0, 2],  [1, 3], [3, 5]

Answer №4

Using splice() to delete array elements directly affects the positions of other elements, causing unexpected output due to shifted indices.

When splice() removes an element from an array, only elements that come after the deleted one are impacted, not those preceding it.

To prevent index conflicts resulting from in-place deletion, a solution is to iterate over the array in reverse order and perform the deletions accordingly.

let test = [0,1,2,4,5];
let test2 = [1,2,3,6,5];
let test3 = [3,4,5,8,9];

let testCopy = [...test];
let testCopy2 = [...test2];
let testCopy3 = [...test3];

for (let i = testCopy.length - 1; i >= 0; i--) {
  if(testCopy[i] !== 0 && testCopy[i] !== 2) { 
    testCopy.splice(i, 1);
    testCopy2.splice(i, 1);
    testCopy3.splice(i, 1);
  }
}

console.log(testCopy, testCopy2, testCopy3); 

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 issue of Segmentation fault in C programming when using an array inside a

Trying to deepen my understanding of C, I am currently delving into writing and experimenting with various code snippets. The current one I am working on is causing me some frustration as I am unsure of what changes need to be made for it to function corre ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Guide on properly accessing a properties file in JavaScript within the project directory?

I am currently working on developing a Chrome Packaged App. My goal is to store the script configuration in a config file within a designated resource directory, and then use Javascript to read this configuration upon startup. For instance: Project We ...

The array in Objective C threw an NSRangeException when attempting to access index 11, which is beyond the bounds of

I implemented a search bar that queries the 4square Api for venues. However, there is an issue where my app crashes with an empty array when I search for a specific word and scroll down. Take a look at my code and the error message below. *** Terminatin ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

Escape from the chains of node.js then() statements

While working with a large amount of externally sourced data, I encounter situations where I need to interrupt the chain of commands and redirect the page. This is an example of my setup: Api file gamesApi.getAllResultsWithTeamInformation(passData) ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

Node.js is unable to handle the contents of an SNS event message

I am encountering an issue while attempting to extract content from a Message in an SNS event within a Node.js Lambda project Below is the code snippet for processing the message: exports.handler = (event, context, callback) => { var message = event. ...

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

The courier stranded in the process of sending a request - express js mongodb

Help needed with postman request issue when condition is not met var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = ...

Implementing the linking of a URL to an HTML hidden button that is dynamically displayed through a Javascript program

I'm currently developing a basic webpage that has a feature allowing users to download the final result as an image file in the last step. To achieve this, I've added a hidden HTML button for downloading the result image and used CSS to set its ...

Wildcard whitelisting in middleware systems

Currently, my app has a global middleware that is functioning properly. However, I am now looking to whitelist certain URLs from this middleware. The URLs that I need to whitelist have the format api/invitation/RANDOMSTRING. To achieve this, I considered ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. https://i.sstatic.net/F3Va4.png What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: h ...

Code needed for blocking screens in Javascript/AJAX

Looking for recommendations for a screen blocker to make my AJAX call synchronous, preventing any user actions until it's completed. Any suggestions? ...

Issue with jQuery tooltip not showing information when there is a space present

I am attempting to display data on a mouse hover event using a jQuery tooltip. The data I have looks like this: {"description":"marry christmas","date":"2016-12-25}" which I received from the server as a JSON string. I am parsing it in my calendar as follo ...

Angular can help you easily convert numbers into a money format

I need assistance in converting a number to Indian currency format. Currently, I have attempted the following: http://plnkr.co/edit/lVJGXyuX0BMvB9QUL5zS?p=preview function formatMoney(credits) { console.log(credits+'credits'); var last ...

Challenges with displaying TreeTable in SAPUI5

I have a case with a single xml view. Inside this view, there is a treetable with two columns. <core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sdf_test.App" xmlns:html="http://www.w3.org/1999/xhtml" ...

Uib-tabset - update triggered by successful HTTP response

I am implementing a modal box with tabs. The first tab allows users to select items and assign them to a user when they click the "Next" button. Upon successful assignment, the next tab automatically displays the configuration for those items. If there is ...

Utilizing Conditional Styling for an Array of Objects within a Textarea in Angular 6

My array contains objects structured as follows: list =[ { name:"name1", value:true } { name:"name2", value:false } { name:"name3", value:true } { name:"name4", value:false ...