-4

To merge two object in to a single. I have this array

var input= [
  {
    code:"Abc",
    a:10
  },

  {
    code:"Abc",
    a:11
  },
  {
    code:"Abcd",
    a:11
  }
]

I need Output as

[
  {code:"Abc",a:[10,11]},
  {code:"Abcd",a:[11]},
]

Please help
uL1
  • 2,117
  • 2
  • 17
  • 28
sunnyn
  • 9
  • 6

2 Answers2

0
function merge(anArray){
    var i, len = anArray.length, hash = {}, result = [], obj;
    // build a hash/object with key equal to code
    for(i = 0; i < len; i++) {
        obj = anArray[i];
        if (hash[obj.code]) {
            // if key already exists than push a new value to an array
            // you can add extra check for duplicates here
            hash[obj.code].a.push(obj.a);
        } else {
            // otherwise create a new object under the key
            hash[obj.code] = {code: obj.code, a: [obj.a]}
        }
    }
    // convert a hash to an array
    for (i in hash) {
        result.push(hash[i]);
    }
    return result;
}

--

// UNIT TEST
var input= [
  {
    code:"Abc",
    a:10
  },

  {
    code:"Abc",
    a:11
  },
  {
    code:"Abcd",
    a:11
  }
];

var expected = [
  {code:"Abc",a:[10,11]},
  {code:"Abcd",a:[11]},
];

console.log("Expected to get true: ",  JSON.stringify(expected) == JSON.stringify(merge(input)));
Sergiy Seletskyy
  • 16,236
  • 7
  • 69
  • 80
0

You need to merge objects that have the same code, so, the task is simple:

var input = [
  {
    code:"Abc",
    a:10
  },

  {
    code:"Abc",
    a:11
  },
  {
    code:"Abcd",
    a:11
  }
];

// first of all, check at the code prop
// define a findIndexByCode Function
function findIndexByCode(code, list) {
  
  for(var i = 0, len = list.length; i < len; i++) {
    if(list[i].code === code) {
      return i;
    }
  }
  
  return -1;
}

var result = input.reduce(function(res, curr) {
  var index = findIndexByCode(curr.code, res);
  
  // if the index is greater than -1, the item was already added and you need to update its a property
  if(index > -1) {
    // update a
    res[index].a.push(curr.a);
  } else {
    
    // otherwise push the whole object
    curr.a = [curr.a];
    res.push(curr);
  }
  
  return res;
}, []);

console.log('result', result);
Hitmands
  • 13,491
  • 4
  • 34
  • 69