Remove elements from an array of items

Object {Results:Array[3]}
Results:Array[3]
[0-2]
    0:Object
           id=1     
           name: "Rick"
           upper:"0.67"
    1:Object
           id=2     
           name:'david'
           upper:"0.46"
    2:Object
           id=3     
           name:'ashley'
           upper:null

In the code snippet above, there is an array of objects displayed along with a variable called delete_id.

delete_id = 1,2

The delete_id variable holds values that correspond to the ids of objects that need to be deleted from the array. The expected output after deletion is shown below:

Object {Results:Array[1]}
Results:Array[3]
[0]
    0:Object
           id=3     
           name:'ashley'
           upper:null

I am seeking assistance on how to achieve this functionality. I have attempted using the following function, but it only deletes the first id in the delete_id variable. For example, if delete_id = 2,3 then only 2 will be deleted. However, I want both 2 and 3 to be removed.

function removeID(delete_id) {
    tabledata = tabledata.filter(function (obj) {
        return delete_id.indexOf(obj.id);
    });

Answer №1

To convert the string delete_id into an array of numeric IDs, you can utilize the functions .split() and .map(). Afterwards, employ .filter() to perform the necessary cleanup.

var users = [
  {
    id: 1,
    name: "Alice",
    score: "0.75"
  }, {
    id: 2,
    name: "Bob",
    score: "0.60"
  }, {
    id: 3,
    name: "Charlie",
    score: null
  }
];

var delete_id = "1,2";

var exclude = delete_id.split(',').map(Number);

users = users.filter(function(user) {
  return exclude.indexOf(user.id) == -1;
});

console.log(users);

Answer №2

function searchObject(arr, val, key) {
            var result = arr.filter(function (object) {
                if (object[key] === val || object[key] == val)
                    return object;
            });
            return result;
        };

To begin with, locate the specific object in the array(tabledata) where value=1(delete_id), and the key in JSON is 'id'

    var foundObject = searchObject(tabledata, delete_id, 'id');

Retrieve the index of that object in the array

    var indexOfObject = tabledata.indexOf(foundObject[0]);

Remove the object from the array based on its index

    tabledata.splice(indexOfObject, 1);

Answer №3

To successfully execute the code, it is necessary to modify the removeID function so that it checks if the index is equal to -1.

function removeID(delete_id) {
  tabledata = tabledata.filter(function(obj) {
    return delete_id.indexOf(obj.id) === -1;  //ensure index is compared with -1
  });
}
var tabledata = [{
  id: 1,
  name: "Rick",
  upper: "0.67"
}, {
  id: 2,
  name: 'david',
  upper: "0.46"
}, {
  id: 3,
  name: 'ashley',
  upper: null
}];

var ids = [1,2];  //defined as an array for clarity
removeID(ids);
console.log(tabledata);

Answer №4

Assuming delete_id is an array of integers, you can use the following code to filter out ids that are present in delete_id.

This code snippet will create a new array called filtered which will only contain objects from tabledata where the id is not found in delete_id. The original tabledata will remain unaffected.

var filtered = tabledata.filter(function(obj) {
   return !(obj.id in delete_id)
})

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

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

How can I locate a Forum or Node using a JWT Token as a reference point?

Could someone please guide me on locating my forum using my JWT token? exports.getByOwnerID = function (req, res, next) { Forum.find({createdBy: req.body.createdBy}) .then(doc => { if(!doc) { return res.status(400).end();} return res.sta ...

generate radio buttons and corresponding labels in real-time

I am trying to automate the creation of elements for each record retrieved from my webservice. <label for="ZAALID_1">Zaal 1</label> <input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHK ...

Using JavaScript to extract data from a PHP script

I'm facing an issue where I'm uncertain about the correct code needed to start extracting data from the PHP script previously parsed in another function. Below is the code snippet: function getExhibitions() { myExhibitionsView = document.get ...

Incorporate a new value into the array with PHP

Looking for some assistance with a quiz that pulls questions from a MySQL database. Can someone help me with this? I need to increase a specific value in the array by adding (+1). <input id="subjectid" name="subjectid[]" value="2" type="checkbox"& ...

Oops! TypeScript error TS2740: The type 'DeepPartial<Quiz>[]' is currently missing key properties from type 'Question': id, question, hasId, save, and a few more

I'm struggling to resolve this error. Can anyone provide guidance on what needs to be corrected in order for this code to function properly? import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm& ...

What prevents reaching the breakpoint?

Take a look at the code snippet provided: #include<stdio.h> /* A program that guesses a number and predicts it. */ int main(void) { short guess=0; _Bool first_time="TRUE"; printf("Guess a number from 1 to 100\n"); printf("Let me guess it&bso ...

Load MP3 or MP4 files upon initial loading

I am trying to automatically play an MP3 audio file as soon as my page loads, ideally using JavaScript. The audio should only play once and at the beginning Despite referencing W3Schools and Mozilla documentation on the audio element, I couldn't get ...

Regular expressions won't produce a match if the string is empty

At present, I am employing the regular expression /^[a-zA-Z.+-. ']+$/ to ascertain the validity of incoming strings. If the incoming string is devoid of content or solely comprises whitespace characters, my objective is for the code to generate an er ...

Building a custom order creation system for Paypal shopping carts with personalized user information

I have a shopping cart where I store an array of my objects. Using a form and jQuery, I serialize all the custom user details. My goal is to integrate the user data gathered from the form (perhaps using payer or payer_info object) and also add my items to ...

The Art of jQuery Data Processing

I'm currently working on extracting data from a form submission. Below is the code I've been using. function handleSubmission() { $("#questionForm").submit(function() { $.post("SubmitQuestion.php", $("#questionForm").serialize()).done(functi ...

Reasons for text not appearing in Firebase

I want to store the text entered into a text field on my website. This is the script I am using to save the data function btnLogin(){ firebase.auth().onAuthStateChanged(function(user){ if(user){ var time = new Date(); var op ...

An error has occurred in the Next.js App: createContext function is not defined

While developing a Next.js application, I keep encountering the same error message TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function every time I try to run my app using npm run dev. This issue arises when attempting to co ...

Encountering an issue in my Next.js application with the app router where I am unable to read properties of undefined, specifically in relation to '

As I develop a basic Rest API in Next.js, my goal is to display "Hello world" in the console for a post api. export const POST = (req: Request) => { console.log('hello world'); }; The error message that appears in my terminal is as follows: ...

What is the method to modify the sender name for an authenticated email?

var nodemailer = require('nodemailer'); // Creating a transporter for sending emails var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '*****@gmail.com', // Your email id ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Automatically save using Jquery when there is a change in the input

Within my CMS (Wordpress) platform, I am implementing a colorpicker. <tr valign="top"> <th scope="row"><?php esc_html_e('Border Color', 'webthesign'); ?></th> <td valign="middle"> <input typ ...

JS: confidential variables (for safely transmitting a score)

Is it possible to retrieve a randomly generated value declared within an anonymous function (IIFE), and if so, how can it be achieved? (function () { // assuming a complex, obscured random function var salt = random()*10000|0; // assuming an event ...

Tips for categorizing items based on their names

Upon receiving a response as shown below: [ {id:1,name:"type1-something"}, {id:2,name:"something-type2"}, {id:3,name:"type3-something"}, {id:4,name:"something-type1"} ] I have an Enum with ...