0

Is there a way I can achieve this code in a more efficient way ? because looping on a very big scores array just to find one score property is very costly

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

scores.forEach(score=>{
    if(score.scoredBy == "youssef"){
      console.log(score);
    }
})
5
  • 2
    Maybe use a loop structure you can break on a match. Commented Jun 13, 2017 at 12:06
  • @Teemu Adding a return statement in the conditional should be enough Commented Jun 13, 2017 at 12:11
  • 1
    @Sebastianb not with forEach.... Commented Jun 13, 2017 at 12:12
  • uff, I'm still asleep! Commented Jun 13, 2017 at 12:14
  • Don't use .forEach, use .find() Commented Jun 13, 2017 at 12:14

1 Answer 1

2

Most efficient way would be to use an object instead of an array where the key is the scoredBy value. No looping, just a lookup.

var scores = { "youssef" : 5, "omar":3 };
console.log(scores["youssef"])

Other ways

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

for (const value of scores) {
  if (value.scoredBy==="youssef") {
    console.log(value.score);
    break;
  }
}

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

var result = scores.find( value => value.scoredBy==="youssef")
console.log(result.score);

Sign up to request clarification or add additional context in comments.

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.