8

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 ?

1
  • What do you want the end result to be? scores is an array, so you can use splice on it. Commented Aug 28, 2013 at 20:02

2 Answers 2

30

Use splice like so:

doc.scores.splice(index, 1);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 This is the proper way to remove an element from an array.
"When the splice method is called with two or more arguments start, deleteCount and (optionally) item1, item2, etc., the deleteCount elements of the array starting at array index start are replaced by the arguments item1, item2, etc. An Array object containing the deleted elements (if any) is returned. " - ecma-international.org/ecma-262/5.1/#sec-15.4.4.12
What should I do if I want to move it to another json variable ??
2

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"]

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.