3

There is an array like this:

var array = [
              {SchoolId: 2  ,GraderId: 465 , SchoolGraderName: "Example1256"},
              {SchoolId: 2  ,GraderId: 654,SchoolGraderName: "Example45"},
              {SchoolId: 2  ,GraderId: 876,SchoolGraderName: "Example895"},
              {SchoolId: 34 ,GraderId: 796,SchoolGraderName:"Example2156"},
              {SchoolId: 45 ,GraderId: 356,SchoolGraderName:"Example315"},
              {SchoolId: 45 ,GraderId: 457,SchoolGraderName:"Example56715"}
              {SchoolId: 45 ,GraderId: 678,SchoolGraderName:"Example37675"}
              {SchoolId: 45 ,GraderId: 465 ,SchoolGraderName:"Example97685615"}
            ]

I am trying to delete the whole objects Where the GraderId is some value (:

$(function() {
            $("#schoolGraders").on("dblclick",
                function() {
                    $.each(array,function(i,r){
                        if (r.GraderId == $(this).val()) {
                            r.removeItem;
                       }
                });
        });

the code above does not work.

Here is the HTML Code:

<select class="form-control" id="schoolGraders" style="width: 80%; height: 200px" 
multiple></select>

I generate the options like this:

item = "";
                $.ajax({
                    type: "GET",
                    url: "address" + $(this).val(),
                    contentType: "application/json",
                    dataType: "json"
                }).done(function (res) {
                    var iteem = "";
                    $.each(res,
                        function (i, r) {
                            iteem += '<option value="' + r.id + 
                             '">' + r.title + '</option>';
                        });
                    $("#graderSchools").html(iteem);
                });

Is there any condition in JavaScript So I can remove objects WHERE the GraderId is some value ?

8
  • Why are we using jQuery? less is more. jQuery made sense five years ago. Not so much now. Commented Sep 6, 2021 at 6:11
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 6, 2021 at 6:13
  • 1
    Rather than using an array, consider using a Set. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 6, 2021 at 6:19
  • 1
    Does this answer your question? How can I remove a specific item from an array? Commented Sep 6, 2021 at 6:28
  • 1
    @M.imp The accepted answer with 14000+ upvotes says "Find the index of the array element you want to remove [....] then remove that index with splice". This totally applies, esp. when combined with the other answers that show how to find the index without using indexOf. Commented Sep 6, 2021 at 8:28

4 Answers 4

2

Something like this perhaps, lets say you want to remove object where GraderId is 876.

var array = [
              {SchoolId: 2  ,GraderId: 465 , SchoolGraderName: "Example1256"},
              {SchoolId: 2  ,GraderId: 654,SchoolGraderName: "Example45"},
              {SchoolId: 2  ,GraderId: 876,SchoolGraderName: "Example895"},
              {SchoolId: 34 ,GraderId: 796,SchoolGraderName:"Example2156"},
              {SchoolId: 45 ,GraderId: 356,SchoolGraderName:"Example315"},
              {SchoolId: 45 ,GraderId: 457,SchoolGraderName:"Example56715"},
              {SchoolId: 45 ,GraderId: 678,SchoolGraderName:"Example37675"},
              {SchoolId: 45 ,GraderId: 465 ,SchoolGraderName:"Example97685615"}
            ]
            
array.forEach((item, index) => {
    if(item.GraderId === 876){
    delete array[index]
  }
})

console.log(array)

Sign up to request clarification or add additional context in comments.

5 Comments

didn't work: $(function() { $("#schoolGraders").on("dblclick", function () { var deletedGraderId = $(this).val(); $("#schoolGraders option[value=" + $(this).val() + "]").remove(); array.forEach((item, index) => { alert("hi"); if (item.GraderId === deletedGraderId) { delete array[index]; } }); }); });
Doesnt the delete in JS only set the element to undefined?
@DragonInTraining No. Delete removes a property from an object. Run this in console let name = {family: "Tosh", first: "Peter"}; delete name.first; name;
DragonInTraining is right, this does exactly the same as array[index] = undefined; and also array.length does not change.
Oh yes, in case of arrays, you are right. Delete does not remove the item, it sets it to undefined. To remove the item, use splice
1

You can use filter():

var array = [
  {SchoolId: 2  ,GraderId: 465 , SchoolGraderName: "Example1256"},
  {SchoolId: 2  ,GraderId: 654,SchoolGraderName: "Example45"},
  {SchoolId: 2  ,GraderId: 876,SchoolGraderName: "Example895"},
  {SchoolId: 34 ,GraderId: 796,SchoolGraderName:"Example2156"},
  {SchoolId: 45 ,GraderId: 356,SchoolGraderName:"Example315"},
  {SchoolId: 45 ,GraderId: 457,SchoolGraderName:"Example56715"}
  {SchoolId: 45 ,GraderId: 678,SchoolGraderName:"Example37675"}
  {SchoolId: 45 ,GraderId: 465 ,SchoolGraderName:"Example97685615"}
]

const filteredArr = array.filter(item => item.GraderId !== $(this).val())

Then maps items to HTML using this filteredArray

9 Comments

does this delete the object where the GraderId is $(this).val() ?
@M.imp yes and will return a new array without those values. Then use the new array to add items to HTML.
Didn't work for me: $("#schoolGraders").on("dblclick", function () { var deletedGraderId = $(this).val(); $("#schoolGraders option[value=" + deletedGraderId + "]").remove(); array = array.filter(item => item.GraderId !== deletedGraderId); }); @Dharmaraj
@M.imp can you provide some HTML around that select?
There is nothing more except the html code I have given in question
|
1

I found the way, Thank you all. Here I wanted to share it to all so everbody can use it.

$("#schoolGraders").on("dblclick",
                function () {

                    var deletedGraderId = $(this).val();

                    var schoolId = $("#selectedSchools").val();

                    $.each(array,
                        function (i, r) {
                            if (r.GraderId == deletedGraderId && r.SchoolId == schoolId) {
                                array.splice(i, 1);
                            }
                        });


                });

Comments

0

The filter method filters an array removing elements that do not pass the condition argument. It's usally the best way to remove array element in js.

I think the main problem in your code is this.val(). this is quite an advanced js concept, as it has multiple meanings depending on the context. In your case, I think it refers to the current value r of your each callback, and not the select element. I prefer evt.currentTarget instead.

The following code must be called inside the done callback as the won't exist before. This kind of error, due to inexistent elements, is silently ignored by jQuery.

var schoolGraders = document.getElementBydId('schoolGraders');
schoolGraders.addEventListener('dblclick', (evt)=> {
    array.filter((obj,i)=>  obj.GraderId != +evt.currentTarget.value)
});

However I'd be vary of using the double click event as it has poor support on Android browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.