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 ?

M.imp
  • 120
  • 11
  • Why are we using jQuery? less is more. jQuery made sense five years ago. Not so much now. – zipzit Sep 06 '21 at 06:11
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice – Pakira Sep 06 '21 at 06:13
  • 1
    Rather than using an array, consider using a Set. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – Brad Sep 06 '21 at 06:19
  • 1
    Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – Peter B Sep 06 '21 at 06:28
  • @PeterB no, it removes only one element, I want to remove an object with a Condition which is fiven GraderId. – M.imp Sep 06 '21 at 06:32
  • how do you render the options? – I am L Sep 06 '21 at 07:35
  • @IamL just added into question – M.imp Sep 06 '21 at 07:40
  • 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. – Peter B Sep 06 '21 at 08:28

4 Answers4

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)
ahsan
  • 1,409
  • 8
  • 11
  • 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]; } }); }); }); – M.imp Sep 06 '21 at 06:16
  • 1
    Doesnt the delete in JS only set the element to undefined? – DragonInTraining Sep 06 '21 at 06:17
  • @DragonInTraining No. [Delete](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) removes a property from an object. Run this in console `let name = {family: "Tosh", first: "Peter"}; delete name.first; name;` – Jose Rui Santos Sep 06 '21 at 07:50
  • DragonInTraining is right, this does ***exactly*** the same as `array[index] = undefined;` and also `array.length` does not change. – Peter B Sep 06 '21 at 08:05
  • 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) – Jose Rui Santos Sep 06 '21 at 08:26
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

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • does this delete the object where the GraderId is $(this).val() ? – M.imp Sep 06 '21 at 06:24
  • @M.imp yes and will return a new array without those values. Then use the new array to add items to HTML. – Dharmaraj Sep 06 '21 at 06:25
  • 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 Sep 06 '21 at 06:27
  • @M.imp can you provide some HTML around that select? – Dharmaraj Sep 06 '21 at 06:28
  • There is nothing more except the html code I have given in question – M.imp Sep 06 '21 at 06:30
  • @M.imp are you trying to add add options to select? Check [this answer](https://stackoverflow.com/questions/10247423/dynamically-set-select-options-with-javascript). That way set the filteredArray to select. – Dharmaraj Sep 06 '21 at 06:33
  • No, I'm trying to delete an object with the condition of equal given GraderId – M.imp Sep 06 '21 at 06:34
  • @M.imp that's not clear what you are trying to delete. I only see a select. What is that 'object' in this case? – Dharmaraj Sep 06 '21 at 06:37
  • Objects are gotten from server (Ajax) and are considered as options – M.imp Sep 06 '21 at 07:10
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);
                            }
                        });


                });
M.imp
  • 120
  • 11
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.

Nice Books
  • 1,675
  • 2
  • 17
  • 21