TheAnimatrix TheAnimatrix - 7 months ago 23
Javascript Question

Merge duplicate array keys in a javascript array

My Array :

{ { PID : [ '1' , '2' , '3' , ..] } , PID : [ '5' , '6' , '7' , '8' ....] , PID : .....} }


This one is a messy array and i would like to have my result combined and clean :

Result :

{ {PID : [ '1' , '2' , '3' , .. , '5' , '6' , '7' and so on ] }}


My Code (PSEUDO):

var links = [];

while( looping of a condition )
{

links.push( function(){

var xArr = [];
var yArr = [];
$.each(function(){
xArr.push(somevalue);
yArr.push(somevalue);
})

return { PID : xArr , SKU : yArr } );

}


And this complex piece of code generated an array with multiple arrays under the duplicate keys 'PID'.

What I've tried:

1.Pushing xArr and yArr into zArr and returning that instead.

I dont have much idea how to proceed , i agree that i am not much of an expert in javascript arrays as of yet . I just ask for a way to go about this issue , more or less a pseudo explanation .

Answer

If you change that to array with objects you can use reduce

var ar = [{PID: ['1', '2', '3', ]}, {PID: ['5', '6', '7', '8']}];

ar = ar.reduce(function(a, el) {
  a.PID = (a.PID || []).concat(el.PID);
  return a
}, {})

console.log(ar);