Vjerci
Vjerci

Reputation: 580

Efficient way of matching array with one to one relationship

If in node we have 2 arrays of objects with one to one relationship and we want to match them efficiently is there some function/s to do the following on cleaner way?

var users = [{id:1},{id:2}]
var userDetails =[{userId:1, eyeColor:'red'},{userId:2, eyeColor:'blue'}]

users.map((u)=>{
    userDetails.find((detail,index)=>{
        return u.id == u.userId ? u.eyeColor = userDetails.splice(index, 1)[0] : false;
    })
})

Upvotes: 0

Views: 84

Answers (1)

digit
digit

Reputation: 4565

I think your code has been simplified enough. Alternatively you can use filter

var filteredArray  = users.filter(function(first){
   return userDetails.filter(function(second){
      return first.id == second.userId;
   });
});

or you can take a look at lodash library for more simplified way

Upvotes: 1

Related Questions