Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values.

Let's say I have the following array:

const idArray = ["935", "933", "930"];

My goal is to remove objects that have an id property matching any value in the idArray and create a new array with the remaining values.

const objectsArray= [
  { 
    name: "Kevin", 
    color: "red", 
    id: "935"
  },
  { 
    name: "Ana", 
    color: "white", 
    id: "815"
  },
  { 
    name: "Maria", 
    color: "silver", 
    id: "035"
  },
  { 
    name: "Victor", 
    color: "red", 
    id: "935"
  },
  { 
    name: "Vanessa", 
    color: "red", 
    id: "933"
  },
]

In this scenario, I want to eliminate the objects with names like Kevin, Vanessa, and Victor, and then return a fresh array containing only Ana and Maria.

This is my progress in the reducer:

case PeopleActions.DELETE_PEOPLE:
  if (action.id.length === 1) {
    return state.filter(people =>
      people.id !== action.id[0]
    );
  } else {
    const deletePeople: any = () => {
      for (let i = 0; i < action.id.length; i++) {
        return state.filter(people =>
          people.id !== action.id[i]
        );
      }
    };
    return deletePeople;
  }

Answer №1

Given that objectsArray is declared as a constant, it cannot be reassigned to a new array due to its const qualifier, rendering the use of filter() not feasible.

In case there is a need to modify the array directly, one approach could be to iterate through the array in reverse order and remove elements using the splice method:

const idArray = ["935", "933", "930"];

const objectsArray= [{   name: "Kevin",   color: "red",   id: "935"},{   name: "Ana",   color: "white",   id: "815"},{   name: "Maria",   color: "silver",   id: "035"},{   name: "Victor",   color: "red",   id: "935"},{   name: "Vanessa",   color: "red",   id: "933"},]

for (let i = objectsArray.length-1; i >=0 ; i--){
    if(idArray.includes(objectsArray[i].id)){
        objectsArray.splice(i,1);
        }
}

console.log(objectsArray);

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 challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

Using Selenium WebDriver with JavaScript: Handling Mouse Events (mouseover, click, keyup) in Selenium WebDriver

I am currently working on integrating Selenium testing for mouse events with dynamically generated elements. Specifically, I am attempting to trigger a "mouseover" event on an element and then interact with some icons within it. However, I have encountere ...

How can I address the issue of an inner content scroll bar?

I am facing an issue with the scroll bar on inner content. When I hover over an arrow on the inner content, the scroll bar appears as desired. However, it changes the content in a way that looks odd. Is there a solution to have a scroll bar on the inner co ...

Eliminate the option to locate columns in the column selector of the mui DataGridPro

Currently, I am creating a data table for a personal project. Utilizing the DataGridPro element from material ui has been quite satisfying, especially with the column selector feature. However, I wish to eliminate the "find column" section. Is it feasibl ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

Guide to utilizing Reduce for obtaining a fresh Array of Objects in Javascript

I am a beginner in coding, so I apologize if this question seems basic. I am working with an array that contains different types of pies along with their prices: pieArr = [blueberry, strawberry, pumpkin, apple] My goal is to create an array of objects re ...

How can you typically verify the type of an object variable in TypeScript?

How can I verify if the obj variable contains all the properties defined in the Person interface? interface Person { name: string; age: number; } const jsonObj = `{ name: "John Doe", age: 30, }`; const obj: Person = JSON.parse(jsonObj); ...

Error encountered in Webpack configuration while using html-webpack-plugin to generate index.html file

I've been experimenting with webpack to bundle project JS files. My goal is to generate an index.html file under the output dist folder using webpack. To achieve this, I followed the instructions provided in the webpack documentation and installed "h ...

Bookshelfjs fails to return a promise when updating multiple data

I am facing an issue when trying to update multiple rows in my database. The problem lies in the fact that the promise does not return anything, even though the data is successfully saved. Below is a snippet of my code: doUpdate: Promise.method(function ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Trouble with clearTimeout function

//Account Creation - Register Button Event $('#registerCreateAccount').on('click', function() { var username = $('#registerUsername').val(); var email = $('#registerEmail').val(); var age = $('#regis ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Error encountered: Provider '$rootScopeProvider' is not recognized - check for typos in the syntax

I am encountering an issue with the templateUrl in AngularJS. When I input this code into my editor and execute it, everything works flawlessly: HTML: <!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8" /> < ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

Error in Angular2: "Promise" name not found despite successful installation of global dependencies

I'm currently developing an application using Angular 2 and Node.js. I've already installed all the necessary dependencies specified in package.json. Inside this file, there is a postinstall command that should install the required dependencies m ...

The Runtime Error encountered in NEXTJS: TypeError - Unable to iterate over 'games' as it is not

Attempting to create my inaugural website that showcases data from an API sans a tutorial. Does it seem like I may have overlooked something? I've successfully fetched the API and confirmed in the console log that the necessary data is present. Howev ...