m.edmondson
m.edmondson

Reputation: 30892

How to group jquery array

I have two arrays that I need to merge together, they look like so:

var array1 = 
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]

and

var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]

I would like to merge them based on x where all properties are kept in the final object.

Expected output:

var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]

I've found $.extend and $.merge but haven't managed to successfully achieve what I need. Any pointers?

Upvotes: 1

Views: 58

Answers (4)

Faly
Faly

Reputation: 13356

Use Object.assign and array.prototype.map:

var array1 = 
[
  {x: "1/12/2011", y: 4149.9},
  {x: "2/12/2011", y: 4094.5},
  {x: "3/12/2011", y: 3606.8}
];

var array2 =
[
  {x: "1/12/2011", z: 3500},
  {x: "2/12/2011", z: 3600},
  {x: "3/12/2011", z: 3700}
]

var merged = array1.map((e, index) => Object.assign({}, e, array2.find(a => a.x === e.x)));

console.log(merged);

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22534

You can array#concat your array and then use array#reduce to merge them based on value of x.

var array1 = [ {x: "1/12/2011", y: 4149.9}, {x: "2/12/2011", y: 4094.5}, {x: "3/12/2011", y: 3606.8} ],
    array2 = [ {x: "1/12/2011", z: 3500}, {x: "2/12/2011", z: 3600}, {x: "3/12/2011", z: 3700} ];

var result = array1
              .concat(array2)
              .reduce((r, o) => {
                r[o.x] = Object.assign({},r[o.x] || {}, o);
                return r;
              },{});
var output = Object.values(result);
console.log(output);

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Just use map method in combination with Object.assign

var array1 = 
[
  {x: "1/12/2011", y: 4149.9},
  {x: "2/12/2011", y: 4094.5},
  {x: "3/12/2011", y: 3606.8}
]
var array2 =
[
  {x: "1/12/2011", z: 3500},
  {x: "2/12/2011", z: 3600},
  {x: "3/12/2011", z: 3700}
]
var expected = array1.map( (a,i) => Object.assign(a, array2.find(b=>b.x == a.x)));
console.log(expected);

Upvotes: 1

Vipin Kumar
Vipin Kumar

Reputation: 6546

While rest of answers are almost correct, but they miss the point of matching x

var array1 = [{
  x: "1/12/2011",
  y: 4149.9
}, {
  x: "2/12/2011",
  y: 4094.5
}, {
  x: "3/12/2011",
  y: 3606.8
}]

var array2 = [{
  x: "1/12/2011",
  z: 3500
}, {
  x: "2/12/2011",
  z: 3600
}, {
  x: "3/12/2011",
  z: 3700
}]

var excpected = array1.map(item => {
  var fromArray2 = array2.filter(array2Item => array2Item.x === item.x)[0];
  item.z = fromArray2.z;
  return item;
})

console.log(excpected);

Upvotes: 1

Related Questions