Home > Net >  Same objects merged one array
Same objects merged one array

Time:12-02

I have input like this. I tried some solutions. But it doesn't work. I need to merge same invoice_nr objects to one array. Also I need other objects another array. All arrays must be another array.

const result = [
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'red'
  },
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'yellow'
  },
  {
    invoice_nr: 17,
    order_id: 5574,
    color: 'green'
  },
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'yellow'
  },
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'blue'
  }
];

But, I need output like this. How can I achieve that in javascript? Array must be like this.

const result = [
  [
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'red'
  },
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'yellow'
  }
  ],
  [
  {
    invoice_nr: 17,
    order_id: 5574,
    color: 'green'
  }
  ],
  [
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'yellow'
  },
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'blue'
  }
  ]
];

CodePudding user response:

You can use .reduce() to build a lookup object where key is the invoice_nr and value is an array. In every iteration look for a key is already exists in lookup object if it is then push to the existing list, if it's not add a new property in the lookup object.

const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ];

const res = result.reduce((a,b) => ((a[b.invoice_nr] ??= []).push(b),a),{});
console.log(Object.values(res));
.as-console-wrapper { max-height: 100% !important }

CodePudding user response:

const result = [
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'red'
  },
  {
    invoice_nr: 16,
    order_id: 5577,
    color: 'yellow'
  },
  {
    invoice_nr: 17,
    order_id: 5574,
    color: 'green'
  },
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'yellow'
  },
  {
    invoice_nr: 18,
    order_id: 5578,
    color: 'blue'
  }
];

let uniq = [];
let res = [];
// get unique ID
result.forEach(i => !uniq.includes(i.invoice_nr) ? uniq.push(i.invoice_nr) : '' );
// filter by ID
uniq.forEach(id => {
    res.push(result.filter(o => o.invoice_nr === id))
})
// that you need in res
console.log(res);

  • Related