join two arrangements based on a property

2

I have two arrangements this way

array1=[{fecha:"2017-01-01", valor:12}, {fecha:"2017-01-02", valor:3 }];
array2 = [{fecha:"2017-01-01", valor:10}, {fecha:"2017-01-03", valor:15 }];

and I want to form a third arrangement from these two by storing the values, as long as the date coincides, so that it looks like this:

array3 = [{fecha:"2017-01-01", valor1:12, valor2:10}, {fecha:"2017-01-02", valor1:3, valor2:0}];

I tried to do it this way:

for (var j in array1.rows){
    var param = array1.rows[j].key;
    // console.log("disparando");
    // console.log(item.key);
    function locate (array) {
        return array.key =param;
    }
    array3.push({
        "y":param,
        "a":array1.rows[j].value,
         "b":array2.rows.find(locate).value,

    });
} 

but I do not get the value it remains the same in the whole array, how can I form the third fix

    
asked by Paul 11.04.2017 в 23:28
source

2 answers

2

You can concatenate both arrays and then filter them depending on the number of occurrences according to the common field (date). Since you use Node.js, you can take advantage of the power of ES6.

Example

array1=[{fecha:"2017-01-01", valor:12}, {fecha:"2017-01-02", valor:3 }];
array2 = [{fecha:"2017-01-01", valor:10}, {fecha:"2017-01-03", valor:15 }];

const finalArray = 
  array1
    .concat(array2)
    .map((el, i, self) => {
      const existences = self.filter(obj => obj.fecha === el.fecha);
      if (existences.length > 1) {
        const $el = Object.assign({}, el, {
         valor: existences.map(obj => obj.valor)
        });
        return $el;
      }
    })
    .filter((el, i, self) => el)
    .filter((el, i, self) => (
      self.findIndex($el => $el.fecha === el.fecha) === i
    ));

console.dir(finalArray);

PD: Instead of value1 , value2 , valorn , etc., I have grouped them as a array so they are better organized.

    
answered by 11.04.2017 / 23:54
source
2

Something like this should be worth it; I have not tested it , but, except for minimal changes, it should work:

function MergeArrays( key, val ) {
  var curr,
      idx,
      gcurr,
      gidx = 1,
      ret = [ ];

  while( gcurr = arguments[++gidx] ) {
    idx = -1;

    while( curr = gcurr[++idx] )
      if( curr[key] == val )
        ret.push( curr );
  }

  return ret;
}

Its use is very simple: MergeArrays (key, val, arr1, ...)

  • key - > name of the property to compare.
  • val - > value to look for.
  • arr1, ... - > 1 or more arrays of objects.

In the case that you expose, it would be:

newArray = MergeArrays( "fecha", "2017-01-01", array1, array2 );
    
answered by 11.04.2017 в 23:39