I want to delete the javascript if there is a match.

Asked 1 years ago, Updated 1 years ago, 21 views

[{
  id: 1,
  data: "hoge"
},{
  id : 3,
  data: "hogehogehoge"
},{
  id: 4,
  data: "fugafuga"
}];

If there is such data, for example, would it be possible to delete the id:3 data?

a=[{
  id: 1,
  data: "hoge"
},{
  id : 3,
  data: "hogehogehoge"
},{
  id: 4,
  data: "fugafuga"
}];


a. removeDataById(3)

↓Results
a = [{
  id: 1,
  data: "hoge"
},{
  id: 4,
  data: "fugafuga"
}];

javascript

2022-09-30 17:23

4 Answers

function removeById(array,id){
  for(vari=array.length-1;i>=0;i--){
    if(array[i].id==id)
      array.splice(i,1)
  }
}

Note the direction of the loop.


2022-09-30 17:23

Although it is not standard, you can also use Array.prototype.filter.
Firefox, Chrome, Opera, Safari, IE9 or higher.
The Array.prototype.filter polyfill is located in Array.prototype.filter() - JavaScript|MDN.

 vara=[{
  id: 1,
  data: "hoge"
}, {
  id : 3,
  data: "hogehogehoge"
}, {
  id: 4,
  data: "fugafuga"
}];

// filter argument —Specifies the function that returns true for the element that you want to leave
varb = a.filter(function(entry) {return entry.id!=3;});

// *Note that a does not change itself, but creates a new array b.
document.querySelector('#result').innerHTML=JSON.stringify(b);
<divid="result"></div>


2022-09-30 17:23

Array.prototype.removeById(id){
  for(vari=this.length-1;i>=0;i--){
    if(this[i].id==id)
      This.splice(i,1)
  }
}


2022-09-30 17:23

Also, I would like to propose a solution with splice.

function removeById(array,id){
  for(vari=array.length-1;i>=0;i--){
    if(array[i].id===id){
      array.splice(i,1);
    }
  }
}

var array = [{
  id: 1,
  data: "hoge"
}, {
  id : 3,
  data: "hogehogehoge"
}, {
  id: 4,
  data: "fugafuga"
}];

removeById(array,3);

console.log(array);


2022-09-30 17:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.