Sergey M
Sergey M

Reputation: 43

Comparing and merging two arrays of objects

I have two arrays of objects(arr1 and arr2). I want to select objects from arr1 where arr1.id == arr2.typeId and add to result arr2.Price

var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]


var arr2 = 
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]

How can I get the following?

var result = 
[{"item":{"id":20,"name":"name1"}, "price":"500"}},
{{"item":{"id":24,"name":"name2"}, "price":"1100"},
{{"item":{"id":28,"name":"name4"}, "price":"1000"}]


var result = arr1.filter(function(obj1){
                        return arr2.some(function(obj2){
                            return obj1.id === obj2.typeId;
                        });
                    })

Upvotes: 0

Views: 87

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386600

You could create an object without any prototypes with Object.create as hash table and push the new object only if both arrays have a common id.

var arr1 = [{ id: 20, name: "name1" }, { id: 24, name: "name2" }, { id: 25, name: "name3" }, { id: 28, name: "name4" }, { id: 29, name: "name5" }],
    arr2 = [{ typeId: 20, Price: 500 }, { typeId: 24, Price: 1100 }, { typeId: 28, Price: 1000 }],
    hash = Object.create(null),
    result = [];

arr1.forEach(function (a) {
    hash[a.id] = a;
});

arr2.forEach(function (a) {
    if (hash[a.typeId]) {
        result.push({ item: hash[a.typeId], price: a.Price });
    }
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

kind user
kind user

Reputation: 41893

Another approach, using Array#forEach.

var arr1 = [{id:20,name:"name1"},{id:24,name:"name2"},{id:25,name:"name3"},{id:28,name:"name4"},{id:29,name:"name5"}],
    arr2 = [{typeId:20,Price:500},{typeId:24,Price:1100},{typeId:28,Price:1e3}],
    result = [];
 
    arr2.forEach(function(v){
      var elem = arr1.find(c => c.id == v.typeId); //find corresponding element from the `arr1` array
      result.push({item: elem, price: v.Price}); //push an object containing `item` and `price` keys into the result array
    });

    console.log(result); //reveal the result

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can use reduce() on arr2 and then check if object with same id exists in arr1 with find().

var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]

var arr2 = 
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]

var result = arr2.reduce(function(r, e) {
  var c = arr1.find(a => e.typeId == a.id)
  if(c) r.push({item: c, price: e.Price})
  return r
}, [])

console.log(result)

Upvotes: 2

Related Questions