Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  138] [ 6]  / answers: 1 / hits: 18325  / 8 Years ago, fri, january 29, 2016, 12:00:00

I've defined an object



var Person = function(name,age,group){
this.name = name,
this.age = age,
this.group = group
}

var ArrPerson = [];
ArrPerson.push(new Person(john,12,M1));
ArrPerson.push(new Person(sam,2,M0));


Now I need an efficient mechanism to identify if the array of objects ArrPerson contains a particular name or not?



I know we can iterate over the array using for loop and check.Assuming the array is huge,is there any other efficient way of doing this?


More From » arrays

 Answers
201

  • use ES5 array methods like map ,filter ,reduce etc

  • use forEach

  • native for loop



Example : filter , map, reduce etc. methods iterate over each item or object in an array,



ArrPerson.filter(function(item){
console.log(item)
});


forEach : also iterates over each item/object in an array



 ArrPerson.forEach(function(key,value){
console.log(key);
console.log(value)
})


The question said huge array , so



native for loop is way faster than any of the above and caching the length can improve by a few ms (milliseconds).



https://jsperf.com/native-map-versus-array-looping



for(var i = 0, len = ArrPerson.length; i < len; i++){

}

[#63514] Wednesday, January 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;