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

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Issue with parsing JSON data for heatmap in Mapbox

Here's the code I'm using: heat = L.heatLayer([], { maxZoom: 12 }).addTo(map); $.getJSON("js/example-single.geojson", function(data) { var geojsosn = L.geoJson(data, { onEachFeature: function (feature, layer) { console.log(f ...

Is the 'wait > remaining' condition ever satisfied in the throttle function of underscore.js?

Check out the library code at line 860: https://github.com/jashkenas/underscore/blob/master/underscore.js if (remaining <= 0 || remaining > wait) Under what circumstance would the second part of this statement be true? Background - This is my firs ...

What is the best way to add a change event to a textarea that is already applied with a filtered one-way binding?

I have a text area that is already linked with a filter, so it will display the correct information when the page loads. Now, I want to update a model when the text area content changes. However, when I add a model and change event, the initial binding sto ...

Can values from a dgrid store be saved in a variable or displayed in the console?

Currently, I am utilizing the dgrid store to display a grid (dgrid 0.4) on my website. Below is the code snippet that I have implemented: require([ 'dojo/_base/declare', 'dojo/Deferred', 'dstore/RequestMemory', ...

Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript? JSON A: { "d": [ {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"}, {"__type":"Web.Controls.Shared.GeneralServic ...

Unable to process jquery AJAX request

Hello, I've been attempting to make a simple ajax call to a method in my code behind. Despite keeping it straightforward for testing purposes, I keep encountering errors. It seems like a basic mistake, but I'm at a loss on how to proceed. The pro ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

A more detailed explanation of Angular's dot notation

I came across a solution for polling data using AngularJS here on stackoverflow. In this particular solution (shown below), a javascript object is used to return the response (data.response). I tried replacing the data object with a simple javascript arra ...

Customize your Material-UI theme with a unique hover effect for contained buttons

Currently, I am in the process of setting up a theme for Material-Ui on my React application. Within the app, there are two types of buttons that I utilize - contained and outlined. The issue lies with the hover effect on the contained button (while the ou ...

Implementing Ajax Like Button functionality in a Ruby on Rails application

I have a Ruby on Rails project that includes a User model and a Content model, among others. I recently implemented a feature where users can "like" content using the acts_as_votable gem. Currently, the liking functionality works as expected but it requir ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

Ways to implement a conditional statement to display a div using JavaScript

Looking for a way to utilize Javascript conditions to toggle the visibility of a div in an HTML5 document? Check out this code snippet below: #demo { width: 500px; height: 500px; background-color: lightblue; display: none; } To set the f ...

Save the retrieved data in a variable and pass the entire JSON object as a prop to a React component

Having some trouble with my code. I need the app to fetch a JSON from an API and pass it as a prop so that each component file can use it and display the element on the screen. The issue is, I can't seem to figure out how to store the fetched informa ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...

Ways to restrict the content div JSON display to only three items

Is it possible to limit the display of items from JSON in the content div to just three? The current code displays all downloaded items, but I want only 3 divs to be returned. <div id="p"></div> $.getJSON('element.json', function(d ...

unusual behavior observed in addEventListener

I have recently delved into learning about the DOM. I have a project in mind where I want to create a website with buttons that, when clicked, play different drum sounds. As part of my experimentation with JavaScript, I wanted to explore the this keyword. ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...