Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element from JSON array

I'm new to nodejs and mongodb. My problem is I've a json of following type

{ 
 _id: 199,
 name: 'Rae Kohout',
 scores: [ 
     { type: 'exam', score: 82.11742562118049 },
     { type: 'quiz', score: 49.61295450928224 },
     { type: 'homework', score: 28.86823689842918 },
     { type: 'homework', score: 5.861613903793295 }
 ]
}

Here I want to compare score for the type 'homework' and remove the homework which has lowest score.To solve this I've written some code like

var low = '';
for(var i=0;i<doc.scores.length;i++)
{
 if(doc.scores[i].type == 'homework'){
   if(low == ''){
      low = doc.scores[i].score;
   }
   if( doc.scores[i].score > low ){
     console.log("index for lowest score is " + i);
     low = '';
   }
 }
}

Now I'm able to find the index for the lowest score, and want to removes values at that index. I tried to use Array.splice() method but that works on Array only. can anyone help me to solve it ?

like image 855
Sadik Avatar asked Aug 28 '13 20:08

Sadik


2 Answers

Use splice like so:

doc.scores.splice(index, 1);
like image 138
zigdawgydawg Avatar answered Oct 04 '22 05:10

zigdawgydawg


The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

if you want to Remove 1 element from index 3. try this

var myArray = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myArray.splice(3, 1);

// removed is ["mandarin"]
// myArray is ["angel", "clown", "drum", "sturgeon"]
like image 34
Shuhad zaman Avatar answered Oct 04 '22 07:10

Shuhad zaman