Guide on deleting objects based on their IDs when the IDs are stored in a separate array using JavaScript

I have two separate arrays. One array contains only integers as IDs (from a searchBox) and the other array contains objects, such as:

categories = [1, 2, 5, 8];

items = [
  { title: 'Hello', description: 'any description you want', categoryId: 1 },
  { title: 'Hello', description: 'any description you want', categoryId: 3 }
]

I've been trying to find a way to remove any item in the second array if its categoryId matches any value in the categories array.

Initially, I attempted to use splice, loop through them (which resulted in an infinite loop), tried indexOf... but after three days, nothing seems to be working.

Is there a method in JS that could return a new array like items.splice(every.categories) (I know this syntax doesn't exist, but is there anything similar in ES6 ?

Answer №1

An efficient solution is to utilize the filter method on the second array and verify the existence of categoryId in the first array.

const categories = [2, 4, 6, 8];
const items = [{ title: 'Howdy', description: 'anything you wish for a description', categoryId: 2 }, { title: 'Howdy', description: 'anything you wish for a description', categoryId: 4 }]

const result = items.filter(item => !categories.find(cat => cat === item.categoryId))

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 most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

Issue with disabling checkboxes in jsTree

Currently utilizing the latest version of jsTree in one of my applications. I would like to have specific checkboxes disabled by default. To achieve this, I am referencing this resource. The jstree code I am using is as follows: $("#"+"div_"+aspectid).js ...

Can you explain the technical distinctions between Express, HTTP, and Connect?

const express = require("express") , app = express() , http = require("http").createServer(app) As I observe, these dependencies are commonly used. As far as I understand it, http serves front-end HTML, while express manages server-side Node.js logic. ...

What are the steps for pairing jsplumb with vuejs?

I successfully implemented the jsPlumb script in an .html file within the script tag and it is functioning properly. <body> <div id="q-app"></div> <!-- built files will be auto injected --> <script> jsPlumb.rea ...

The error message being displayed states that 'null' cannot be used as an object when evaluating 'response.productType'

Hey everyone, I'm fairly new to working with Ajax and I've encountered an error in my code that says: TypeError: 'null' is not an object (evaluating 'response.productType'). I'm not sure why this is happening. Below is th ...

Encountering an issue with googleapis in Vue.js: Error - The argument labeled as "original" must be of type Function

Attempting to retrieve rows from a Google Spreadsheet using googleapis for a Vue project. I have set up the necessary project and service account credentials in the Google console. However, upon clicking the button, I encounter this error: TypeError: The " ...

Find and replace string words containing special characters such as $ or !

Looking to process an input string in a specific way - // Input string - 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$' // Processed string 'My pen cost is <penCost> manufactured ...

Switching from dark mode to light mode when reloading or navigating to a new page

Hello everyone. I've successfully implemented a dark mode toggle on my website, but I'm facing an issue where the mode resets whenever I navigate to a new page or refresh the current page. Can anyone help me figure out how to prevent this from ...

Tips for creating equal height columns in Bootstrap 4

Working with Bootstrap 4 Beta in an attempt to create two columns that maintain full height regardless of screen size. The code below functions perfectly, ensuring both columns maintain full height across all devices. However, upon inserting the bootstra ...

`Toggling between Vue components using buttons`

I am attempting to switch between two vue components using the following code: <template> <button @click="selected = 'A', console.log(selected)">A</button> <button @click="selected = 'B', cons ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

What could be the reason behind Cesium viewer's failure to show a model after I upload it?

My application features a 3D map of a city with an "Add building" button. Upon clicking this button, a model of a building should be inserted into the map. However, all I see is a selection marker at the intended location without the actual building appea ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...

No parameters have been found in the $router.push function

Imagine this scenario: this.$root.$router.push({ path: '/dashboard', params: { errors: 'error' }, query: { test: 'test' } }) Within my component, I am using the above code to redirect to another URL when an err ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...