+ 6
Remove object from array with specified value! HELP!!
I want to remove an object from array using person.splice(person.indexOf(i), 1) along with filter method. Given iter = 1; var i = iter; Filter person that has dead property equals to true then splice them all. Increment iter in order to refresh() the page and so on. However i still got person.name error in result. I want to know to fix these codes. if(persons[0].dead){ var body = document.querySelector("body") body.style.display = " none" }else{ const deadPerson = persons.filter(element => element.dead) for(var i of deadPerson){ persons.splice(persons.indexOf(i), 1) } refresh() iter += 1 } https://code.sololearn.com/WtfV0I5pTiF9/?ref=app
6 Respostas
+ 5
The numberOfPersons variable needs to be updated as objects are being removed from the persons array.
+ 3
Would you mind putting the bits you want help with into another code? It just makes it easier for us to read/debug. đđ
+ 3
//second part
var iter = 1
function friendsAging(){
for(var i = iter; i < numberOfPersons; i++){
persons[i].aging()
persons[i].eat()
persons[i].study()
persons[i].sleep()
persons[i].walk()
//find person from persons that is working
const workingPerson = persons.filter(element => element.working)
for(var i of workingPerson){
i.work()
} // [{name:"Doe", working: true}]
//find person from persons that has a disease
const sickPerson = persons.filter(element => element.disease.length > 0);
for(var i of sickPerson){
i.doctor()
}; // [{name:"John", disease:["insomnia"]}]
}
refresh()
}
+ 3
//third part
function relations(){
for(var i = iter; i < numberOfPersons; i++){
document.getElementById("relations").innerHTML +=
"<div id='friends-name'>" +
persons[i].name +
"</div>" +
"<br>" +
" đ : " + persons[i].age +
"<br>" +
" ⥠: " + persons[i].energy +
"<br>" +
" đ” : " + persons[i].money +
"<br>" +
" đ§ : " + persons[i].iq +
"<br>" +
" †: " + persons[i].health +
"<br>" +
" đ : " + persons[i].relation +
"<br>" +
" đ : " + persons[i].dead +
"<br>" +
" đ» : " + persons[i].working +
"<br>" +
" đ· : " + persons[i].disease +
"<div id='con-btn' onclick='conversation(" + i + ")'>đ„ Conversation</div>" +
"<div id='gm-btn' onclick='giveMoney(" + i + ")'>đž Give Money</div>" +
"<div id='argue-btn' onclick='argue(" + i + ")'>đ€Ź Argue</div>" +
"<br>"
}
}
window.onload = function(){
relations()
}
function refresh(){
document.getElementById("relations").innerHTML =''
+ 2
//first part
if(restart === false){
if(persons[0].dead){
var body = document.querySelector("body")
body.style.display = " none"
}else{
const deadPerson = persons.filter(element => element.dead);
for(var i of deadPerson){
persons.splice(persons.indexOf(i), 1)
}
refresh()
iter += 1
}
}
+ 2
Its now working. Thanks for answering!