You Ma
You Ma

Reputation: 189

What is the most efficient way to loop on properties in array of objects?

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);
    }
})

Upvotes: 0

Views: 60

Answers (1)

epascarello
epascarello

Reputation: 207511

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);

Upvotes: 2

Related Questions