Create a grouped array using two different arrays

I have below two arrays:

array1 = [{
   "type":"test",
   "name":"name1"},
 {
   "type":"dev",
    "name":"name2"}]

array2=[{
         "type":"test",
         "name":"name3"},
        {
         "type":"dev",
         "name":"name4"},
        {
         "type":"prod",
         "name":"name5"}]

I want to group two arrays with a β€œtype” and create a new array like this:

finalArray=[{
             "type":"test",
             "info":[{
                      "type":"test",
                      "name":"name1"}],
                    [{
                      "type":"test",
                      "name":"name3"
                    }]},
             {
              "type":"dev",
              "info":[{
                       "type":"dev",
                       "name":"name2"}],
                     [{
                       "type":"dev",
                       "name":"name4"}]},
             {
              "type":"prod",
              "info":[],
                     [{
                       "type":"prod",
                        "name":"name5"}]
               }]

In any case, I can achieve this using javascript, angularjs2, lodash, jquery. I can group and create a new object, as indicated in using lodash.groupBy. How to add my own keys for group output?

But only always I want to output data from the second array in index = 1 from "info" and first in index = 0. If any of the array does not have a "type", then the array "info" should have empty / zero values.

+4
4

, javascript, , lodash. . "", . .

[] . , javascript.

// get uniques type from two arrays
const uniqueTypes = new Set(array1
                          .concat(array2)
                          .map(x => x.type));

// loop the types, find item in both array
// group it
let result = Array.from(uniqueTypes).reduce((acc, curr) => {
    const item1 = array1.find(x => x.type === curr);
    const item2 = array2.find(x => x.type === curr);

    const info1 = item1 ? [item1] : [];
    const info2 = item2 ? [item2] : [];

    acc = acc.concat({ type: curr, info: [info1, info2] });

    return acc;
}, []);


console.log(result);

jsbin : https://jsbin.com/mobezogaso/edit?js,console

+1

_.mapValues ,

var res =  _.chain(array1)
    .concat(array2)
    .groupBy('type')
    .mapValues(function(val, key) {
        return {
            type: key,
            info: val
        };
    })
    .values()
    .value();
+2

:). , !

var array1 = [
{
"type":"test",
"name":"name1"
},
{
"type":"dev",
"name":"name2"
}
]

var array2 = [
{
"type":"test",
"name":"name3"
},
{
"type":"dev",
"name":"name4"
},
{
"type":"prod",
"name":"name5"
}
]


var newArray = array1.concat(array2);
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arrTypes = [];
var finalArray = [];
var someArray = [];

for(var i in newArray)
{
 if (arrTypes.indexOf(newArray[i].type) === -1){
   arrTypes.push(newArray[i].type);
 }

 if(newArray[i].type === "test"){
   arr1.push(newArray[i]);
 }
 else if(newArray[i].type === "dev"){
   arr2.push(newArray[i]);
 }
 else if(newArray[i].type === "prod"){
   arr3.push(newArray[i]);
 }
}
someArray.push(arr1);
someArray.push(arr2);
someArray.push(arr3);

for(var j = 0; j < someArray.length; j++){
	finalArray.push({
		"type": arrTypes[j],
		"info": someArray[j]
	});
}
console.log(finalArray);
+1

(?) ES6:

  • Map,
  • - () - ( )
  • Using a spread to convert an input iterator to an array
  • Array#Map array of records for type / information objects

const array1 = [{"type":"test","name":"name1"},{"type":"dev","name":"name2"}];
const array2=[{"type":"test","name":"name3"},{"type":"dev","name":"name4"},{"type":"prod","name":"name5"}];

const result = [...array1.concat(array2).reduce((r, o) => {
    r.has(o.type) ? r.get(o.type).push(o) : r.set(o.type, [o]);
    return r;
  }, new Map).entries()]
  .map(([type, info]) => ({
    type, info
  }));

console.log(result);
Run code
0
source

Source: https://habr.com/ru/post/1664800/


All Articles